### Start GenBackgroundService in Rust Source: https://docs.rs/pingora/0.6.0/pingora/services/background/struct The `start_service` function, part of the `Service` trait implementation, defines the logic executed when the pingora server starts this background service. It handles setup and asynchronous execution. ```Rust fn start_service<'life0, 'async_trait>( &'life0 mut self, _fds: Option>>, shutdown: Receiver, _listeners_per_fd: usize, ) -> Pin + Send + 'async_trait>> where 'life0: 'async_trait, GenBackgroundService: 'async_trait, ``` -------------------------------- ### Service Start and Management Source: https://docs.rs/pingora/0.6.0/pingora/services/listening/struct Details on starting a service and accessing its properties. ```APIDOC ## Service Lifecycle and Properties ### Description Methods related to the lifecycle of a service, including starting it and accessing its metadata. ### Methods #### `start_service<'life0, 'async_trait>(...) -> Pin + Send + 'async_trait>>` This function will be called when the server is ready to start the service. #### `name(&self) -> &str` The name of the service, just for logging and naming the threads assigned to this service. #### `threads(&self) -> Option` The preferred number of threads to run this service. ``` -------------------------------- ### Downstream Module Initialization API Source: https://docs.rs/pingora/0.6.0/pingora/proxy/prelude/trait Allows for the setup and configuration of downstream HTTP modules before the server starts. ```APIDOC ## fn init_downstream_modules(modules: &mut HttpModules) ### Description Set up downstream modules. In this phase, users can add or configure HttpModules before the server starts up. In the default implementation of this method, ResponseCompressionBuilder is added and disabled. ### Method N/A (Associated function, typically called during server initialization) ### Endpoint N/A ### Parameters - **modules** (*&mut HttpModules*) - Required - A mutable reference to the HttpModules object to configure. ### Request Example None ### Response None (Modifies the `modules` object in place). ``` -------------------------------- ### Get Request Summary Source: https://docs.rs/pingora/0.6.0/pingora/proxy/prelude/struct Returns a summary of the request, including the method, path, and Host header. ```APIDOC ## GET /request_summary ### Description Returns a summary of the request, including the method, path, and Host header. ### Method GET ### Endpoint /request_summary ### Response #### Success Response (200) - **summary** (string) - A string containing the request method, path, and Host header. #### Response Example ```json { "summary": "GET /example.com/path HTTP/1.1" } ``` ``` -------------------------------- ### Get Request Summary Source: https://docs.rs/pingora/0.6.0/pingora/proxy/prelude/struct Returns a string summarizing the request, including its method, path, and Host header. ```rust pub fn request_summary(&self) -> String ``` -------------------------------- ### Start Method for BackgroundService (Rust) Source: https://docs.rs/pingora/0.6.0/pingora/services/background/trait Details the `start` method signature for the `BackgroundService` trait. This method is invoked when the Pingora server starts services and allows for asynchronous operations or waiting for a shutdown signal. ```rust fn start<'life0, 'async_trait>( &'life0 self, shutdown: Receiver, ) -> Pin + Send + 'async_trait>> where 'life0: 'async_trait, Self: 'async_trait, ``` -------------------------------- ### Pingora Service Start Implementation Source: https://docs.rs/pingora/0.6.0/pingora/services/listening/struct Implementation of the `start_service` function for the `Service` trait in Pingora. This function is called when the server is ready to begin executing the service, managing threads and file descriptors. ```Rust fn start_service<'life0, 'async_trait>( &'life0 mut self, fds: Option>>, shutdown: Receiver, listeners_per_fd: usize, ) -> Pin + Send + 'async_trait>> where 'life0: 'async_trait, Service: 'async_trait, ``` -------------------------------- ### Manually Create Box from NonNull with System Allocator (Rust) Source: https://docs.rs/pingora/0.6.0/pingora/cache/type Provides an example of manually creating a Box from scratch using the system allocator and a NonNull pointer. Requires specific nightly features. ```rust #![feature(allocator_api, box_vec_non_null, slice_ptr_get)] use std::alloc::{Allocator, Layout, System}; unsafe { let non_null = System.allocate(Layout::new::())?.cast::(); // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `non_null`. non_null.write(5); let x = Box::from_non_null_in(non_null, System); } ``` -------------------------------- ### PrometheusHttpApp Implementation Source: https://docs.rs/pingora/0.6.0/pingora/apps/http_app/trait An example implementation of the ServeHttp trait for Prometheus metrics. ```APIDOC ### impl ServeHttp for PrometheusHttpApp This block indicates that the `PrometheusHttpApp` struct implements the `ServeHttp` trait. Specific details of its implementation would be found elsewhere in the documentation. ``` -------------------------------- ### Manually Create Box from Scratch with Global Allocator (Rust) Source: https://docs.rs/pingora/0.6.0/pingora/cache/type This example shows how to manually allocate memory using the global allocator and then construct a `Box` from it. This method requires careful handling of memory deallocation and deconstruction. ```Rust #![feature(box_vec_non_null)] use std::alloc::{alloc, Layout}; use std::ptr::NonNull; unsafe { let non_null = NonNull::new(alloc(Layout::new::()).cast::()) .expect("allocation failed"); // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `non_null`. non_null.write(5); let x = Box::from_non_null(non_null); } ``` -------------------------------- ### Create an empty Extensions instance Source: https://docs.rs/pingora/0.6.0/pingora/cache/meta/struct Demonstrates how to create a new, empty `Extensions` object using the `new()` associated function. This is the starting point for adding custom data. ```rust let mut ext = Extensions::new(); ``` -------------------------------- ### Implement Service Trait for GenBackgroundService in Rust Source: https://docs.rs/pingora/0.6.0/pingora/services/background/struct Shows the implementation of the `Service` trait for `GenBackgroundService`. This enables the service to be managed and started within the pingora server lifecycle. ```Rust impl Service for GenBackgroundService where A: BackgroundService + Send + Sync + 'static, ``` -------------------------------- ### Create Intermediate TLS Settings in Rust Source: https://docs.rs/pingora/0.6.0/pingora/listeners/tls/struct Provides a constructor for TlsSettings that takes string slices, likely for intermediate certificate and key paths. It returns a Result, indicating potential errors during setup. ```rust pub fn intermediate(_: &str, _: &str) -> Result> ``` -------------------------------- ### Session Initialization Methods Source: https://docs.rs/pingora/0.6.0/pingora/proxy/prelude/struct Provides methods for creating new `Session` instances, either from a stream or with specific modules, primarily for testing and mocking purposes. ```APIDOC ## Session Initialization ### `pub fn new_h1(stream: Box) -> Session` Create a new Session from the given Stream. This function is mostly used for testing and mocking. ### `pub fn new_h1_with_modules(stream: Box, downstream_modules: &HttpModules) -> Session` Create a new Session from the given Stream with modules. This function is mostly used for testing and mocking. ``` -------------------------------- ### Get Mutable Slice of Buffer Source: https://docs.rs/pingora/0.6.0/pingora/lb/health_check/type Returns a mutable slice of the buffer starting from the current position. The slice's length is between 0 and the remaining writable bytes. This allows in-place modification of buffer contents. ```rust fn chunk_mut(&mut self) -> &mut UninitSlice ``` -------------------------------- ### Service Structure and Creation Source: https://docs.rs/pingora/0.6.0/pingora/services/listening/struct Details on the `Service` struct and its constructors for creating new services. ```APIDOC ## Struct Service ### Description The type of service that is associated with a list of listening endpoints and a particular application. ### Fields * `threads` (Option) - The number of preferred threads. `None` to follow global setting. ### Methods #### `new(name: String, app_logic: A) -> Service` Create a new `Service` with the given application. #### `with_listeners(name: String, listeners: Listeners, app_logic: A) -> Service` Create a new `Service` with the given application and the given `Listeners`. ``` -------------------------------- ### BufRef Methods: Get Slice and Bytes Source: https://docs.rs/pingora/0.6.0/pingora/utils/struct Provides methods to retrieve a sub-slice of the underlying buffer. `get` returns a standard slice, while `get_bytes` returns a `Bytes` type, which is an O(1) operation that also increments the buffer's reference count. ```Rust pub fn get<'a>(&self, buf: &'a [u8]) -> &'a [u8] Return a sub-slice of `buf`. pub fn get_bytes(&self, buf: &Bytes) -> Bytes Return a slice of `buf`. This operation is O(1) and increases the reference count of `buf`. ``` -------------------------------- ### Pingora Service Creation Methods Source: https://docs.rs/pingora/0.6.0/pingora/services/listening/struct Provides methods for creating new `Service` instances in Pingora. These include creating a basic service, a service with specified listeners, and methods to add various types of listening endpoints like TCP, TLS, and Unix domain sockets. ```Rust pub fn new(name: String, app_logic: A) -> Service pub fn with_listeners( name: String, listeners: Listeners, app_logic: A, ) -> Service pub fn add_tcp(&mut self, addr: &str) pub fn add_tcp_with_settings(&mut self, addr: &str, sock_opt: TcpSocketOptions) pub fn add_uds(&mut self, addr: &str, perm: Option) pub fn add_tls( &mut self, addr: &str, cert_path: &str, key_path: &str, ) -> Result<(), Box> pub fn add_tls_with_settings( &mut self, addr: &str, sock_opt: Option, settings: TlsSettings, ) pub fn add_address(&mut self, addr: ServerAddress) ``` -------------------------------- ### Box::from() Example Source: https://docs.rs/pingora/0.6.0/pingora/cache/type Demonstrates converting a value into a Box using the From trait. ```rust let x = 5; let boxed = Box::new(5); assert_eq!(Box::from(x), boxed); ``` -------------------------------- ### Manually Create Box from Scratch with System Allocator (Rust) Source: https://docs.rs/pingora/0.6.0/pingora/cache/type Shows how to manually create a Box using the system allocator. This involves allocating memory, writing the value, and then creating the Box. Requires 'allocator_api' and 'slice_ptr_get' features. ```rust #![feature(allocator_api, slice_ptr_get)] use std::alloc::{Allocator, Layout, System}; unsafe { let ptr = System.allocate(Layout::new::())?.as_mut_ptr() as *mut i32; // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `ptr`, though for this // simple example `*ptr = 5` would have worked as well. ptr.write(5); let x = Box::from_raw_in(ptr, System); } ``` -------------------------------- ### Box ExactSizeIterator Methods Source: https://docs.rs/pingora/0.6.0/pingora/cache/type Implements ExactSizeIterator for Box, providing methods to get the exact length of the iterator. ```rust fn len(&self) -> usize fn is_empty(&self) -> bool ``` -------------------------------- ### Stream Access Source: https://docs.rs/pingora/0.6.0/pingora/proxy/prelude/struct Method to get the underlying stream for an HTTP/1 session. ```APIDOC ## GET /session/stream ### Description Gets a reference to the `Stream` that the HTTP/1 session is operating upon. Returns `None` if the HTTP session is over HTTP/2. ### Method GET ### Endpoint `/session/stream` ### Response #### Success Response (200) - **Option<&Box>** - A reference to the underlying stream if it's an HTTP/1 session, otherwise None. #### Response Example ```json { "stream_reference": "stream_object_reference" } ``` ``` -------------------------------- ### Consume Box to Get Inner Value (Rust) Source: https://docs.rs/pingora/0.6.0/pingora/cache/type Consumes the Box, returning the wrapped value. This is a nightly-only experimental API. ```rust #![feature(box_into_inner)] let c = Box::new(5); assert_eq!(Box::into_inner(c), 5); ``` -------------------------------- ### CommandFactory Implementations for Box Source: https://docs.rs/pingora/0.6.0/pingora/listeners/type Provides methods for creating command-line applications from a Box where T implements CommandFactory. ```APIDOC ## CommandFactory Implementations for Box ### Description Provides methods for creating command-line applications from a Box where T implements CommandFactory. ### Methods #### `into_app` - **Description**: Deprecated, replaced with `CommandFactory::command`. - **Return Type**: `App<'help>` #### `into_app_for_update` - **Description**: Deprecated, replaced with `CommandFactory::command_for_update`. - **Return Type**: `App<'help>` #### `command` - **Description**: Build a `Command` that can instantiate `Self`. - **Return Type**: `App<'help>` #### `command_for_update` - **Description**: Build a `Command` that can update `self`. - **Return Type**: `App<'help>` ``` -------------------------------- ### Box::new_uninit_in Source: https://docs.rs/pingora/0.6.0/pingora/protocols/type Constructs a new box with uninitialized contents in the provided allocator. This is an experimental nightly-only API. ```APIDOC ## POST /Box::new_uninit_in ### Description Constructs a new box with uninitialized contents in the provided allocator. This is an experimental nightly-only API. ### Method POST ### Endpoint /Box::new_uninit_in ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **alloc** (A) - Required - The allocator to use. ### Request Example ```json { "alloc": "A" } ``` ### Response #### Success Response (200) - **Box, A>** (Box, A>) - The newly created box with uninitialized contents. #### Response Example ```json { "box": "Box, A>" } ``` ``` -------------------------------- ### Get Retry Buffer Contents Source: https://docs.rs/pingora/0.6.0/pingora/proxy/prelude/struct Retrieves the contents of the retry buffer, if available. ```APIDOC ## GET /get_retry_buffer ### Description Retrieves the contents of the retry buffer, if available. ### Method GET ### Endpoint /get_retry_buffer ### Response #### Success Response (200) - **buffer** (Option) - The contents of the retry buffer, or None if not available. #### Response Example ```json { "buffer": "686578616d706c65" } ``` ``` -------------------------------- ### Box::new_uninit_in Source: https://docs.rs/pingora/0.6.0/pingora/listeners/type Constructs a new box with uninitialized contents in the provided allocator. This is a nightly-only experimental API. ```APIDOC ## POST /box/new_uninit_in ### Description Constructs a new box with uninitialized contents in the provided allocator. This is a nightly-only experimental API. (`allocator_api`) ### Method POST ### Endpoint /box/new_uninit_in #### Parameters ##### Request Body - **alloc** (A) - Required - The allocator to use. ### Request Example ```json { "alloc": "System" } ``` ### Response #### Success Response (200) - **uninit_box** (Box, A>) - The new box with uninitialized contents. #### Response Example ```json { "uninit_box": "" } ``` ### Examples ```rust #![feature(allocator_api)] use std::alloc::System; let mut five = Box::::new_uninit_in(System); // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5) ``` ``` -------------------------------- ### Any Trait Implementation (Rust) Source: https://docs.rs/pingora/0.6.0/pingora/cache/eviction/lru/struct Provides a method to get the `TypeId` of a type. This is a blanket implementation for all types that are `'static + ?Sized`. ```Rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Consume Box and Get Inner Value (Rust) Source: https://docs.rs/pingora/0.6.0/pingora/listeners/type Consumes the Box, returning the inner value. This is a nightly-only experimental API. ```rust #![feature(box_into_inner)] let c = Box::new(5); assert_eq!(Box::into_inner(c), 5); ``` -------------------------------- ### Rust: Blanket Implementation for TryFrom and TryInto Source: https://docs.rs/pingora/0.6.0/pingora/protocols/http/v1/server/struct Provides blanket implementations for `TryFrom` and `TryInto`. `TryFrom` allows attempting a conversion that might fail, returning a `Result`. `TryInto` is the inverse, also returning a `Result`. ```rust impl TryFrom for T where U: Into, { type Error = Infallible; fn try_from(value: U) -> Result>::Error> { // Implementation details for try_from conversion } } impl TryInto for T where U: TryFrom, { type Error = >::Error; fn try_into(self) -> Result>::Error> { U::try_from(self) } } ``` -------------------------------- ### Session Downstream Access Source: https://docs.rs/pingora/0.6.0/pingora/proxy/prelude/struct Methods to get mutable or immutable references to the downstream session. ```APIDOC ## Session Downstream Access ### `pub fn as_downstream_mut(&mut self) -> &mut Session` Source ### `pub fn as_downstream(&self) -> &Session` Source ``` -------------------------------- ### Create Static Service Discovery Instance (Rust) Source: https://docs.rs/pingora/0.6.0/pingora/lb/discovery/struct Provides methods to create instances of the `Static` service discovery. `new` takes a `BTreeSet` of `Backend`s, while `try_from_iter` accepts an iterator of items that can be converted into socket addresses. ```rust pub fn new(backends: BTreeSet) -> Box ``` ```rust pub fn try_from_iter(iter: T) -> Result, Error> where T: IntoIterator, A: ToSocketAddrs ``` -------------------------------- ### HttpSession Request Information Source: https://docs.rs/pingora/0.6.0/pingora/protocols/http/v1/server/struct Utility methods to get information about the current HTTP request. `request_summary` provides a formatted string for logging, `is_upgrade_req` checks for upgrade requests, and `get_header_bytes` returns raw header bytes. ```Rust pub fn request_summary(&self) -> String pub fn is_upgrade_req(&self) -> bool pub fn get_header_bytes(&self, name: impl AsHeaderName) -> &[u8] ``` -------------------------------- ### Implement Any for T in Rust Source: https://docs.rs/pingora/0.6.0/pingora/protocols/l4/socket/enum Provides the `type_id` method to get the `TypeId` of a type `T`. This is useful for runtime type identification. Requires `T` to be `'static + ?Sized`. ```rust impl Any for T where T: 'static + ?Sized, { fn type_id(&self) -> TypeId } ``` -------------------------------- ### Retrieve Backends from Static Discovery (Rust) Source: https://docs.rs/pingora/0.6.0/pingora/lb/discovery/struct The `get` method on the `Static` struct returns the current collection of backends. This method provides read-only access to the static set of `Backend`s managed by the discovery instance. ```rust pub fn get(&self) -> BTreeSet ``` -------------------------------- ### Random Selection Algorithm Source: https://docs.rs/pingora/0.6.0/pingora/lb/selection/algorithms/struct Provides documentation for the Random selection algorithm used in Pingora's load balancing. This algorithm is available only when the 'lb' crate feature is enabled. ```APIDOC ## Struct Random ### Description Random selection algorithm for load balancing. Available on `crate feature`lb` only. ### Method N/A (Struct definition) ### Endpoint N/A (Struct definition) ### Parameters N/A ### Request Example N/A ### Response N/A ## Trait Implementations ### impl SelectionAlgorithm for Random #### fn new() -> Random ##### Description Create a new implementation of the Random selection algorithm. ##### Method N/A (Associated function) ##### Endpoint N/A ##### Parameters N/A ##### Request Example N/A ##### Response - **Random** (Random) - A new instance of the Random selection algorithm. #### fn next(&self, _key: &[u8]) -> u64 ##### Description Return the next index of backend. The caller should perform modulo to get the valid index of the backend. ##### Method N/A (Method) ##### Endpoint N/A ##### Parameters - **_key** ( &[u8] ) - Optional - The key to use for selection (not used by Random). ##### Request Example N/A ##### Response - **u64** - The next backend index (un-moduled). ``` -------------------------------- ### Get Shared Reference from Box (Rust) Source: https://docs.rs/pingora/0.6.0/pingora/protocols/type Converts a shared reference to `Box` into a shared reference to the inner `T`. This is part of the `AsRef` trait implementation. ```rust fn as_ref(&self) -> &T ``` -------------------------------- ### Get Mutable Reference from Box (Rust) Source: https://docs.rs/pingora/0.6.0/pingora/protocols/type Converts a mutable reference to `Box` into a mutable reference to the inner `T`. This is part of the `AsMut` trait implementation. ```rust fn as_mut(&mut self) -> &mut T ``` -------------------------------- ### CommandFactory for Box Source: https://docs.rs/pingora/0.6.0/pingora/cache/type Defines methods for creating command-line application structures from a `Box`. `command` builds a command for instantiation, and `command_for_update` builds one for updating an existing instance. Note that `into_app` and `into_app_for_update` are deprecated. ```rust fn into_app<'help>() -> App<'help> Deprecated, replaced with `CommandFactory::command` fn into_app_for_update<'help>() -> App<'help> Deprecated, replaced with `CommandFactory::command_for_update` fn command<'help>() -> App<'help> Build a `Command` that can instantiate `Self`. fn command_for_update<'help>() -> App<'help> Build a `Command` that can update `self`. ``` -------------------------------- ### RequestHeader Build Methods Source: https://docs.rs/pingora/0.6.0/pingora/http/prelude/struct Methods for creating new `RequestHeader` instances with specified method and path. ```APIDOC ## RequestHeader Build Methods ### `pub fn build(method: impl TryInto, path: &[u8], size_hint: Option) -> Result>` **Description:** Create a new `RequestHeader` with the given method and path. The `path` can be non UTF-8. **Parameters:** * `method` (impl TryInto): The HTTP method for the request. * `path` (&[u8]): The request path as a byte slice. * `size_hint` (Option): An optional hint for initial size allocation. **Returns:** `Result>` - A new `RequestHeader` or an error. ### `pub fn build_no_case(method: impl TryInto, path: &[u8], size_hint: Option) -> Result>` **Description:** Create a new `RequestHeader` with the given method and path without preserving header case. This is more space-efficient than `Self::build()` and suitable for HTTP/2 sessions where header case doesn't matter. **Parameters:** * `method` (impl TryInto): The HTTP method for the request. * `path` (&[u8]): The request path as a byte slice. * `size_hint` (Option): An optional hint for initial size allocation. **Returns:** `Result>` - A new `RequestHeader` or an error. ``` -------------------------------- ### Get Writable Bytes Count Source: https://docs.rs/pingora/0.6.0/pingora/lb/health_check/type Returns the number of bytes that can be written to the buffer from the current position until the end. This indicates the available space for writing data. ```rust fn remaining_mut(&self) -> usize ``` -------------------------------- ### Create GenBackgroundService Instance in Rust Source: https://docs.rs/pingora/0.6.0/pingora/services/background/struct Provides a constructor function `new` for creating instances of GenBackgroundService. This service is designed to run within the pingora runtime. ```Rust pub fn new(name: String, task: Arc) -> GenBackgroundService ``` -------------------------------- ### Value and Write Implementations Source: https://docs.rs/pingora/0.6.0/pingora/cache/type Documentation for `Value` and `Write` trait implementations for `Box`, covering value recording and buffer writing operations. ```APIDOC ## Value and Write Implementations for Box ### Description This section documents the implementations of the `Value` and `Write` traits for `Box`, enabling tracing value recording and asynchronous/synchronous buffer writing operations. ### `impl Value for Box where T: Value + ?Sized` #### `fn record(&self, key: &Field, visitor: &mut dyn Visit)` Visits this value with the given `Visitor`. This method is part of the `Value` trait and is used for serialization or inspection of values. - **`key`** (*Field*) - The key associated with the value being visited. - **`visitor`** (*`&mut dyn Visit`*) - A mutable reference to the visitor object. ### `impl Write for Box where T: Write + Unpin + ?Sized` (Asynchronous) #### `fn poll_write(self: Pin<&mut Box>, cx: &mut Context<'_>, buf: &[u8]) -> Poll>` Asynchronously attempts to write bytes from `buf` into the destination writer. This method is part of the `Write` trait for asynchronous operations. - **`self`** (*`Pin<&mut Box>`*) - A pinned mutable reference to the `Box` writer. - **`cx`** (*`&mut Context<'_>`*) - The context for polling the operation. - **`buf`** (*`&[u8]`*) - The buffer containing the bytes to write. #### `fn poll_write_vectored(self: Pin<&mut Box>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>]) -> Poll>` Asynchronously attempts to write bytes from a slice of buffers (`bufs`) into the destination writer. This method is optimized for writing multiple contiguous blocks of data. - **`self`** (*`Pin<&mut Box>`*) - A pinned mutable reference to the `Box` writer. - **`cx`** (*`&mut Context<'_>`*) - The context for polling the operation. - **`bufs`** (*`&[IoSlice<'_>]`*) - A slice of `IoSlice` buffers to write. #### `fn is_write_vectored(&self) -> bool` Returns `true` if this writer has an efficient `poll_write_vectored` implementation, indicating it can benefit from vectorized writes. #### `fn poll_flush(self: Pin<&mut Box>, cx: &mut Context<'_>) -> Poll>` Asynchronously attempts to flush any buffered data to the underlying writer. This ensures that all data is written to its destination. - **`self`** (*`Pin<&mut Box>`*) - A pinned mutable reference to the `Box` writer. - **`cx`** (*`&mut Context<'_>`*) - The context for polling the operation. #### `fn poll_shutdown(self: Pin<&mut Box>, cx: &mut Context<'_>) -> Poll>` Asynchronously attempts to shut down the writer, completing any pending operations. - **`self`** (*`Pin<&mut Box>`*) - A pinned mutable reference to the `Box` writer. - **`cx`** (*`&mut Context<'_>`*) - The context for polling the operation. ### `impl Write for Box where W: Write + ?Sized` (Synchronous) #### `fn write(&mut self, buf: &[u8]) -> Result` Synchronously writes bytes from `buf` into the destination writer. Returns the number of bytes written. - **`buf`** (*`&[u8]`*) - The buffer containing the bytes to write. #### `fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result` Synchronously writes bytes from a slice of buffers (`bufs`) into the destination writer. This method is optimized for writing multiple contiguous blocks of data. - **`bufs`** (*`&[IoSlice<'_>]`*) - A slice of `IoSlice` buffers to write. #### `fn is_write_vectored(&self) -> bool` Returns `true` if this writer has an efficient `write_vectored` implementation, indicating it can benefit from vectorized writes. This is a nightly-only experimental API. #### `fn flush(&mut self) -> Result<(), Error>` Synchronously flushes any buffered data to the underlying writer. This ensures that all data is written to its destination. #### `fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>` Attempts to write an entire buffer (`buf`) into this writer. This method repeatedly calls `write` until the entire buffer is written or an error occurs. - **`buf`** (*`&[u8]`*) - The buffer containing the bytes to write. #### `fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>` Attempts to write multiple buffers (`bufs`) into this writer. This is a nightly-only experimental API. - **`bufs`** (*`&mut [IoSlice<'_>]`*) - A mutable slice of `IoSlice` buffers to write. #### `fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<(), Error>` Writes a formatted string into this writer, returning any error encountered. - **`fmt`** (*`Arguments<'_>`*) - The formatted arguments to write. #### `fn by_ref(&mut self) -> &mut Self` Creates a “by reference” adapter for this instance of `Write`. This allows mutable borrowing of the writer. ### `impl WriteColor for Box where T: WriteColor + ?Sized` #### `fn supports_color(&self) -> bool` Returns `true` if and only if the underlying writer supports colors. #### `fn supports_hyperlinks(&self) -> bool` Returns `true` if and only if the underlying writer supports hyperlinks. #### `fn set_color(&mut self, spec: &ColorSpec) -> Result<(), Error>` Sets the color settings of the writer. This allows for colored output. - **`spec`** (*`&ColorSpec`*) - The color specification to set. #### `fn set_hyperlink(&mut self, link: &HyperlinkSpec<'_>) -> Result<(), Error>` Sets the current hyperlink of the writer. This allows for hyperlink output. - **`link`** (*`&HyperlinkSpec<'_>`*) - The hyperlink specification to set. ``` -------------------------------- ### Get the number of items in pingora Extensions Source: https://docs.rs/pingora/0.6.0/pingora/cache/meta/struct Shows the usage of the `len` method to retrieve the current number of stored extensions within an `Extensions` object. ```rust let mut ext = Extensions::new(); assert_eq!(ext.len(), 0); ext.insert(5i32); assert_eq!(ext.len(), 1); ``` -------------------------------- ### BufRef Constructor Source: https://docs.rs/pingora/0.6.0/pingora/utils/struct The `new` function is a public constructor for creating a `BufRef` instance. It takes a starting index and a length to define the bounds of the referenced slice within a buffer. ```Rust pub fn new(start: usize, len: usize) -> BufRef Initialize a `BufRef` that can reference a slice beginning at index `start` and has a length of `len`. ``` -------------------------------- ### Create HTTP Proxy Service (Rust) Source: https://docs.rs/pingora/0.6.0/pingora/proxy/fn Creates a pingora Service for an HTTP proxy using a user-implemented ProxyHttp. This service can be directly hosted by a pingora_core::server::Server. Requires the 'proxy' crate feature. ```Rust pub fn http_proxy_service( conf: &Arc, inner: SV, ) -> Service> where SV: ProxyHttp, { } ``` -------------------------------- ### Initialize ResponseCompressionCtx Source: https://docs.rs/pingora/0.6.0/pingora/protocols/http/compression/struct Creates a new ResponseCompressionCtx instance. This function allows setting the compression level (0 to disable), enabling decompression, and preserving the ETag header. Configuration is applied across all supported algorithms. ```rust pub fn new( compression_level: u32, decompress_enable: bool, preserve_etag: bool, ) -> ResponseCompressionCtx ``` -------------------------------- ### Rust: Blanket Implementation for PolicyExt Source: https://docs.rs/pingora/0.6.0/pingora/protocols/http/v1/server/struct Implements `PolicyExt` for any type `T` where `T` is `?Sized`. The `and` and `or` methods allow combining policies to create new policies based on logical AND and OR operations. ```rust impl PolicyExt for T where T: ?Sized, { fn and(self, other: P) -> And where T: Policy, P: Policy, { // Implementation details for combining policies with AND } fn or(self, other: P) -> Or where T: Policy, P: Policy, { // Implementation details for combining policies with OR } } ``` -------------------------------- ### Get Single-Precision Float (Native-Endian) Source: https://docs.rs/pingora/0.6.0/pingora/lb/health_check/type Retrieves a 4-byte IEEE754 single-precision floating-point number from a buffer in native-endian byte order. Can be more efficient if native endianness is used. ```rust fn try_get_f32_ne(&mut self) -> Result ``` -------------------------------- ### Get Unsigned N-byte Integer (Native-Endian) Source: https://docs.rs/pingora/0.6.0/pingora/lb/health_check/type Retrieves an unsigned integer of specified byte length from a buffer in native-endian byte order. This can be more efficient for local processing. ```rust fn try_get_uint_ne(&mut self, nbytes: usize) -> Result ``` -------------------------------- ### Box::try_new_uninit_in Source: https://docs.rs/pingora/0.6.0/pingora/listeners/type Constructs a new box with uninitialized contents in the provided allocator, returning an error if the allocation fails. This is a nightly-only experimental API. ```APIDOC ## POST /box/try_new_uninit_in ### Description Constructs a new box with uninitialized contents in the provided allocator, returning an error if the allocation fails. This is a nightly-only experimental API. (`allocator_api`) ### Method POST ### Endpoint /box/try_new_uninit_in #### Parameters ##### Request Body - **alloc** (A) - Required - The allocator to use. ### Request Example ```json { "alloc": "System" } ``` ### Response #### Success Response (200) - **uninit_box** (Box, A>) - The new box with uninitialized contents. #### Error Response (e.g., 400) - **error** (AllocError) - An error indicating the allocation failed. #### Response Example ```json { "uninit_box": "" } ``` ### Examples ```rust #![feature(allocator_api)] use std::alloc::System; let mut five = Box::::try_new_uninit_in(System)?; // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5); ``` ``` -------------------------------- ### Clone Methods for Box Source: https://docs.rs/pingora/0.6.0/pingora/protocols/type Methods for cloning Box instances. ```APIDOC ## impl Clone for Box ### Description Provides methods for cloning `Box` instances. ### Methods #### fn clone(&self) -> Box ##### Description Returns a new box with a `clone()` of this box’s contents. ##### Examples ```rust let x = Box::new(5); let y = x.clone(); // The value is the same assert_eq!(x, y); // But they are unique objects assert_ne!(&*x as *const i32, &*y as *const i32); ``` #### fn clone_from(&mut self, source: &Box) ##### Description Copies `source`’s contents into `self` without creating a new allocation. ##### Examples ```rust let x = Box::new(5); let mut y = Box::new(10); let yp: *const i32 = &*y; y.clone_from(&x); // The value is the same assert_eq!(x, y); // And no allocation occurred assert_eq!(yp, &*y); ``` ``` -------------------------------- ### Get Signed 128-bit Integer (Little-Endian) Source: https://docs.rs/pingora/0.6.0/pingora/lb/health_check/type Retrieves a signed 128-bit integer from a buffer in little-endian byte order. This function is useful for data serialized with little-endianness. ```rust fn try_get_i128_le(&mut self) -> Result ``` -------------------------------- ### HttpSession API Source: https://docs.rs/pingora/0.6.0/pingora/protocols/http/v1/server/struct Provides methods for creating, reading, writing, and managing HTTP/1.x server sessions. ```APIDOC ## HttpSession ### Description The HTTP 1.x server session handles the lifecycle of an HTTP request and response on a single connection. ### Methods #### `new(underlying_stream: Box) -> HttpSession` Creates a new HTTP server session from an established stream (TCP or TLS). The session must call `read_request()` before other operations. #### `read_request(&mut self) -> Result, Box>` Reads and parses the request header. Returns `Ok(Some(n))` on success, `Ok(None)` if the client closes the connection without sending data, and `Err` on failure. #### `req_header(&self) -> &RequestHeader` Returns a reference to the parsed `RequestHeader`. Panics if called before `read_request()`. #### `req_header_mut(&mut self) -> &mut RequestHeader` Returns a mutable reference to the parsed `RequestHeader`. Panics if called before `read_request()`. #### `get_header(&self, name: impl AsHeaderName) -> Option<&HeaderValue>` Retrieves the value of a specific header. Returns the first value if multiple headers with the same name exist. Use `req_header().header.get_all(name)` for all values. #### `request_summary(&self) -> String` Returns a string representation of the request (e.g., `$METHOD $PATH, Host: $HOST`), useful for logging. #### `is_upgrade_req(&self) -> bool` Checks if the request is an upgrade request (e.g., for WebSockets). #### `get_header_bytes(&self, name: impl AsHeaderName) -> &[u8]` Retrieves the raw bytes of a request header. Returns an empty byte slice if the header does not exist. #### `read_body_bytes(&mut self) -> Result, Box>` Reads the request body as bytes. Returns `Ok(None)` when there is no more body data. #### `drain_request_body(&mut self) -> Result<(), Box>` Drains the request body. Returns `Ok(())` when the body is fully consumed or not present. #### `is_body_done(&mut self) -> bool` Indicates whether the entire request body has been read. #### `is_body_empty(&mut self) -> bool` Checks if the request body is empty. Accurate after the request header is read. #### `write_response_header(&mut self, header: Box) -> Result<(), Box>` Writes the response header to the client. Can be called multiple times for 1xx informational responses (excluding 101). #### `write_response_header_ref(&mut self, resp: &ResponseHeader) -> Result<(), Box>` A reference-based version of `write_response_header()`. #### `response_written(&self) -> Option<&ResponseHeader>` Returns the response header if it has already been sent. #### `is_upgrade(&self, header: &ResponseHeader) -> Option` Determines if the response is an upgrade, a refused upgrade, or not an upgrade request. #### `get_keepalive_timeout(&self) -> Option` Retrieves the keep-alive timeout value for the connection. #### `will_keepalive(&self) -> bool` Checks if the connection will be kept alive for reuse. #### `respect_keepalive(&mut self)` Applies keep-alive settings based on the client's request headers (e.g., `Connection: keep-alive` or `Connection: Close`). #### `write_body(&mut self, buf: &[u8]) -> Result, Box>` Writes a chunk of the response body to the client. Returns `Ok(None)` if writing more bytes would exceed the `Content-Length`. #### `finish_body(&mut self) -> Result, Box>` Signals the end of the response body. Flushes buffers and sends the final chunk for chunked encoding. Closes client body reading for upgraded sessions. #### `body_bytes_sent(&self) -> usize` Returns the number of response body bytes sent to the client. #### `body_bytes_read(&self) -> usize` Returns the number of request body bytes read from the client. #### `retry_buffer_truncated(&self) -> bool` Indicates if the retry buffer was truncated. ``` -------------------------------- ### Get Unsigned 128-bit Integer (Native-Endian) Source: https://docs.rs/pingora/0.6.0/pingora/lb/health_check/type Retrieves an unsigned 128-bit integer from a buffer in the system's native endian byte order. This can be more efficient on some architectures. ```rust fn try_get_u128_ne(&mut self) -> Result ``` -------------------------------- ### Clone Implementations for Box Source: https://docs.rs/pingora/0.6.0/pingora/listeners/type Provides methods for cloning Box instances. ```APIDOC ## Clone Implementations for Box ### Description Provides methods for cloning Box instances. ### Methods #### `clone` - **Description**: Returns a new box with a `clone()` of this box’s contents. - **Return Type**: `Box` - **Example**: ```rust let x = Box::new(5); let y = x.clone(); assert_eq!(x, y); assert_ne!(&*x as *const i32, &*y as *const i32); ``` #### `clone_from` - **Description**: Copies `source`’s contents into `self` without creating a new allocation. - **Parameters**: - `source` (&Box) - The source box to copy from. - **Example**: ```rust let x = Box::new(5); let mut y = Box::new(10); let yp: *const i32 = &*y; y.clone_from(&x); assert_eq!(x, y); assert_eq!(yp, &*y); ``` ``` -------------------------------- ### Get Keep-Alive Duration Source: https://docs.rs/pingora/0.6.0/pingora/proxy/prelude/struct Retrieves the current keep-alive timeout duration. Returns `None` if keep-alive is disabled. This is not applicable for HTTP/2 connections. ```APIDOC ## GET /keepalive ### Description Retrieves the current keep-alive timeout duration. Returns `None` if keep-alive is disabled. This is not applicable for HTTP/2 connections. ### Method GET ### Endpoint /keepalive ### Response #### Success Response (200) - **duration** (Option) - The keep-alive timeout duration in seconds, or None if disabled. #### Response Example ```json { "duration": 60 } ``` ``` -------------------------------- ### Insert and retrieve data with pingora Extensions Source: https://docs.rs/pingora/0.6.0/pingora/cache/meta/struct Illustrates the usage of `insert` and `get` methods for managing data within an `Extensions` object. It shows how to add new data and retrieve existing data by its type, including handling cases where the data is not present. ```rust let mut ext = Extensions::new(); assert!(ext.insert(5i32).is_none()); assert!(ext.insert(4u8).is_none()); assert_eq!(ext.insert(9i32), Some(5i32)); assert!(ext.get::().is_none()); ext.insert(5i32); assert_eq!(ext.get::(), Some(&5i32)); ``` -------------------------------- ### Get Connection Keepalive (Rust) Source: https://docs.rs/pingora/0.6.0/pingora/protocols/http/server/enum Retrieves the configured keepalive timeout duration. Returns `None` if keepalive is disabled. This setting is not applicable to HTTP/2. ```rust pub fn get_keepalive(&self) -> Option ``` -------------------------------- ### Get Type ID using Any Trait in Rust Source: https://docs.rs/pingora/0.6.0/pingora/apps/struct Retrieves the `TypeId` of the current instance. This is part of the Any trait implementation, enabling runtime type inspection. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Rust Pingora Session Constructor Functions Source: https://docs.rs/pingora/0.6.0/pingora/proxy/prelude/struct Provides functions for creating new `Session` instances. `new_h1` is for basic session creation from a stream, primarily for testing. `new_h1_with_modules` allows initialization with specific HTTP modules, offering more control over session behavior, also mainly for testing purposes. ```rust pub fn new_h1(stream: Box) -> Session // Create a new Session from the given Stream // This function is mostly used for testing and mocking. ``` ```rust pub fn new_h1_with_modules( stream: Box, downstream_modules: &HttpModules, ) -> Session // Create a new Session from the given Stream with modules // This function is mostly used for testing and mocking. ``` -------------------------------- ### Create a New Server Configuration (Rust) Source: https://docs.rs/pingora/0.6.0/pingora/server/configuration/struct A constructor function to create a new `ServerConf` instance with default settings. It returns an `Option`, indicating that configuration might not always be available or successfully initialized. This is useful for starting with a baseline configuration. ```rust pub fn new() -> Option ``` -------------------------------- ### Adjust Specific Algorithm Preserve ETag Source: https://docs.rs/pingora/0.6.0/pingora/protocols/http/compression/struct Adjusts the ETag preservation setting for a specific algorithm. This method will panic if the response body has already started being encoded. ```rust pub fn adjust_algorithm_preserve_etag( &mut self, algorithm: Algorithm, enabled: bool, ) ``` -------------------------------- ### Create Connector Instance - Pingora Rust Source: https://docs.rs/pingora/0.6.0/pingora/connectors/http/v1/struct Provides the constructor for the 'Connector' struct in Rust. It takes an optional 'ConnectorOptions' argument and returns a new 'Connector' instance. This is the primary way to initialize a connector. ```rust pub fn new(options: Option) -> Connector ``` -------------------------------- ### Get Single-Precision Float (Little-Endian) Source: https://docs.rs/pingora/0.6.0/pingora/lb/health_check/type Retrieves a 4-byte IEEE754 single-precision floating-point number from a buffer in little-endian byte order. Useful for data streams with little-endian floats. ```rust fn try_get_f32_le(&mut self) -> Result ```