Skip to main content

ProductOSServer

Struct ProductOSServer 

Source
pub struct ProductOSServer<S, E, X>
where E: Executor<X> + ExecutorPerform<X> + Timer,
{ /* private fields */ }
Expand description

The main server struct for Product OS Server

ProductOSServer provides a complete web server implementation with support for:

  • HTTP and HTTPS protocols
  • Routing and middleware
  • TLS/SSL via rustls
  • WebSockets and Server-Sent Events
  • Command-and-control distributed networking (with controller feature)
  • Compression, CORS, CSRF, and security headers

§Type Parameters

  • S: The shared state type (must be Clone + Send + Sync + 'static)
  • E: The executor type implementing Executor traits
  • X: The underlying executor context type

§Examples

§Basic HTTP Server

use product_os_server::{ProductOSServer, StatusCode, Response, Body};
use product_os_server::ServerConfig;
use product_os_async_executor::TokioExecutor;

let config = ServerConfig::new();
let mut server: ProductOSServer<(), TokioExecutor, _> = 
    ProductOSServer::new_with_config(config);

async fn handler() -> Result<Response<Body>, StatusCode> {
    Ok(Response::new(Body::empty()))
}

server.add_get("/", handler);

§Server with Shared State

use product_os_server::{ProductOSServer, StatusCode, Response};
use product_os_server::ServerConfig;
use product_os_async_executor::TokioExecutor;

#[derive(Clone)]
struct AppState {
    counter: std::sync::Arc<parking_lot::Mutex<i32>>,
}

let state = AppState {
    counter: std::sync::Arc::new(parking_lot::Mutex::new(0)),
};

let config = ServerConfig::new();
let mut server: ProductOSServer<AppState, TokioExecutor, _> = 
    ProductOSServer::new_with_state_with_config(config, state);

Implementations§

Source§

impl<E, X> ProductOSServer<(), E, X>
where E: Executor<X> + ExecutorPerform<X> + Timer + 'static,

Source

pub fn new_with_executor_with_config( executor: Option<Arc<E>>, config: ServerConfig, ) -> Self

Creates a new server with a custom executor and configuration.

This constructor allows specifying a custom executor for handling async operations.

§Arguments
  • executor - Optional executor Arc. If None, will panic.
  • config - Server configuration
Source

pub fn new_with_executor(executor: Option<Arc<E>>) -> Self

Creates a new server with a custom executor and default configuration.

§Arguments
  • executor - Optional executor Arc. If None, will panic.
Source§

impl<S, E, X> ProductOSServer<S, E, X>
where S: Clone + Send + Sync + 'static, E: Executor<X> + ExecutorPerform<X> + Timer + 'static,

Source

pub fn new_with_executor_with_state_with_config( executor: Option<Arc<E>>, config: ServerConfig, state: S, ) -> Self

Creates a new server with custom executor, state, and configuration.

This is the most flexible constructor, allowing full customization of executor, state, and configuration.

§Arguments
  • executor - Optional executor Arc. If None, will panic.
  • config - Server configuration including network, security, compression settings
  • state - Shared state that will be available to all handlers
Source

pub fn new_with_executor_with_state(executor: Option<Arc<E>>, state: S) -> Self

Creates a new server with custom executor and state.

Uses default configuration.

§Arguments
  • executor - Optional executor Arc. If None, will panic.
  • state - Shared state available to all handlers
Source

pub fn set_certificate(&mut self, certificate_config: &Option<Certificate>)

Sets or updates the TLS certificate configuration.

§Arguments
  • certificate_config - Optional certificate configuration. If None, will generate self-signed.
Source

pub fn set_security(&mut self, security: Option<Security>)

Sets or updates the security configuration.

This includes settings for security headers, CSRF protection, etc.

§Arguments
  • security - Optional security configuration. If None, security features are disabled.
Source

pub fn get_router(&mut self) -> &mut ProductOSRouter<S>

Retrieves a mutable reference to the router.

This allows direct manipulation of the underlying router for advanced use cases.

§Returns

A mutable reference to the ProductOSRouter.

§Examples
let router = server.get_router();
// Perform advanced router operations
Source

pub fn add_route(&mut self, path: &str, service_handler: MethodRouter<S>)

Adds a route with a method router.

§Arguments
  • path - The URL path for the route (e.g., “/api/users”)
  • service_handler - The method router handling the route
§Examples
use product_os_router::MethodRouter;

async fn handler() -> Result<Response<Body>, StatusCode> {
    Ok(Response::new(Body::empty()))
}

let method_router = MethodRouter::new().get(handler);
server.add_route("/test", method_router);
Source

pub fn set_fallback(&mut self, service_handler: MethodRouter<S>)

Sets a fallback handler for unmatched routes.

The fallback handler is called when no route matches the incoming request. This is typically used to return a 404 Not Found response.

§Arguments
  • service_handler - The method router for handling unmatched routes
§Examples
use product_os_router::MethodRouter;

async fn not_found() -> Result<Response<Body>, StatusCode> {
    Err(StatusCode::NOT_FOUND)
}

let fallback = MethodRouter::new().fallback(not_found);
server.set_fallback(fallback);
Source

pub fn add_get<H, T>(&mut self, path: &str, handler: H)
where H: Handler<T, S>, T: 'static,

Adds a GET request handler.

Convenience method for adding a handler that responds to GET requests.

§Arguments
  • path - The URL path (e.g., “/api/users”)
  • handler - The async function handling the request
§Examples
async fn get_users() -> Result<Response<Body>, StatusCode> {
    Ok(Response::new(Body::empty()))
}

server.add_get("/api/users", get_users);
Source

pub fn add_post<H, T>(&mut self, path: &str, handler: H)
where H: Handler<T, S>, T: 'static,

Adds a POST request handler.

Convenience method for adding a handler that responds to POST requests.

§Arguments
  • path - The URL path (e.g., “/api/users”)
  • handler - The async function handling the request
§Examples
async fn create_user(Json(user): Json<User>) -> Result<Response<Body>, StatusCode> {
    Ok(Response::new(Body::empty()))
}

server.add_post("/api/users", create_user);
Source

pub fn add_handler<H, T>(&mut self, path: &str, method: Method, handler: H)
where H: Handler<T, S>, T: 'static,

Adds a handler for a specific HTTP method and path.

§Arguments
  • path - The URL path
  • method - The HTTP method (GET, POST, PUT, DELETE, etc.)
  • handler - The async function to handle the request
§Examples
async fn patch_handler() -> Result<Response<product_os_server::Body>, StatusCode> {
    Ok(Response::new(product_os_server::Body::empty()))
}
server.add_handler("/resource", Method::PATCH, patch_handler);
Source

pub fn set_fallback_handler<H, T>(&mut self, handler: H)
where H: Handler<T, S>, T: 'static,

Sets a fallback handler that will be called for unmatched routes.

§Arguments
  • handler - The async function to handle unmatched requests
§Examples
async fn not_found() -> Result<Response<product_os_server::Body>, StatusCode> {
    Err(StatusCode::NOT_FOUND)
}
server.set_fallback_handler(not_found);
Source

pub fn add_handlers<H, T>(&mut self, path: &str, handlers: BTreeMap<Method, H>)
where H: Handler<T, S>, T: 'static,

Adds multiple handlers for different HTTP methods on the same path.

§Arguments
  • path - The URL path
  • handlers - A map of HTTP methods to their handlers
§Examples
// Note: This API requires handlers of the same type. In practice,
// use add_get, add_post, etc. for different handler implementations.
async fn handler() -> Result<Response<Body>, StatusCode> {
    Ok(Response::new(Body::empty()))
}
 
// Use add_handler for each method instead:
server.add_handler("/resource", Method::GET, handler);
server.add_handler("/resource", Method::POST, handler);
Source

pub fn set_router(&mut self, router: ProductOSRouter<S>)
where S: Clone + Send + Sync + 'static,

Sets the entire router, replacing the existing one.

§Arguments
  • router - The new router to use
§Examples
let new_router = ProductOSRouter::new();
server.set_router(new_router);
Source

pub async fn create_https_server( &mut self, serve_on_main_thread: bool, listen_all_interfaces: bool, custom_port: Option<u16>, custom_router: Option<Router>, with_connect_info: bool, ) -> Result<(), Box<dyn Error + Send + Sync>>

Creates and starts an HTTPS server.

Internal method for creating HTTPS servers with TLS support. Use start() instead for normal server initialization.

§Arguments
  • _serve_on_main_thread - Whether to block the main thread
  • _listen_all_interfaces - Whether to listen on all network interfaces
  • _custom_port - Optional custom port number
  • _custom_router - Optional custom router to use
  • _with_connect_info - Whether to extract connection info
Source

pub async fn create_http_server( &mut self, serve_on_main_thread: bool, listen_all_interfaces: bool, custom_port: Option<u16>, custom_router: Option<Router>, with_connect_info: bool, ) -> Result<(), Box<dyn Error + Send + Sync>>

Creates and starts an HTTP server.

Internal method for creating HTTP servers. Use start() instead for normal server initialization.

§Arguments
  • serve_on_main_thread - Whether to block the main thread
  • listen_all_interfaces - Whether to listen on all network interfaces
  • custom_port - Optional custom port number
  • custom_router - Optional custom router to use
  • with_connect_info - Whether to extract connection info
Source

pub async fn init_stores(&mut self)

Initializes data stores.

Internal method for store initialization. Currently a no-op but reserved for future store initialization logic.

Source

pub fn get_config(&self) -> ServerConfig

Gets the server configuration.

§Returns

A clone of the current server configuration.

§Examples
let current_config = server.get_config();
println!("Server port: {}", current_config.network.port);
Source

pub fn update_config(&mut self, config: ServerConfig)

Updates the server configuration.

§Arguments
  • config - The new configuration to apply
§Examples
let mut new_config = ServerConfig::new();
new_config.network.port = 8080;
server.update_config(new_config);
Source

pub fn get_base_url(&self) -> Uri

👎Deprecated since 0.0.53: Use try_get_base_url() which returns Result instead of panicking

Gets the base URL of the server.

Returns the URL where the server is accessible, constructed from the configuration’s host and port settings.

§Returns

A Uri representing the server’s base URL.

§Examples
let base_url = server.get_base_url();
println!("Server available at: {}", base_url);
Source

pub fn try_get_base_url(&self) -> Result<Uri>

Returns the base URL as a Uri, or an error if URL parsing fails.

This is the non-panicking version of get_base_url.

Auto Trait Implementations§

§

impl<S, E, X> Freeze for ProductOSServer<S, E, X>
where S: Freeze,

§

impl<S, E, X> !RefUnwindSafe for ProductOSServer<S, E, X>

§

impl<S, E, X> Send for ProductOSServer<S, E, X>
where S: Send, X: Send,

§

impl<S, E, X> Sync for ProductOSServer<S, E, X>
where S: Sync, X: Sync,

§

impl<S, E, X> Unpin for ProductOSServer<S, E, X>
where S: Unpin, X: Unpin,

§

impl<S, E, X> UnsafeUnpin for ProductOSServer<S, E, X>
where S: UnsafeUnpin,

§

impl<S, E, X> !UnwindSafe for ProductOSServer<S, E, X>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CastSlice<'_, T> for T

Source§

fn cast_slice(selves: &[T]) -> &[T]

Source§

impl<T> CastSliceMut<'_, T> for T

Source§

fn cast_slice_mut(selves: &mut [T]) -> &mut [T]

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more