Skip to main content

ServerBuilder

Struct ServerBuilder 

Source
pub struct ServerBuilder { /* private fields */ }

Implementations§

Source§

impl ServerBuilder

Source

pub fn create(host: &str, port: u16, setup: FoxtiveSetup) -> ServerBuilder

Source

pub fn app(self, app: &str) -> Self

Source

pub fn tracing(self, config: Tracing) -> Self

Source

pub fn workers(self, workers: usize) -> Self

Set number of workers to start.

By default http server uses 2

Source

pub fn backlog(self, backlog: i32) -> Self

Set the maximum number of pending connections.

This refers to the number of clients that can be waiting to be served. Exceeding this number results in the client getting an error when attempting to connect. It should only affect servers under significant load.

Generally set in the 64-2048 range. Default value is 2048.

This method should be called before bind() method call.

Source

pub fn keep_alive(self, keep_alive: Seconds) -> Self

Set server keep-alive setting.

By default keep alive is set to a 5 seconds.

Source

pub fn client_timeout(self, timeout: u16) -> Self

Set request read timeout in seconds.

Defines a timeout for reading client request headers. If a client does not transmit the entire set headers within this time, the request is terminated with the 408 (Request Time-out) error.

To disable timeout set value to 0.

By default client timeout is set to 3 seconds.

Source

pub fn client_disconnect(self, timeout: u16) -> Self

Set server connection disconnect timeout in seconds.

Defines a timeout for shutdown connection. If a shutdown procedure does not complete within this time, the request is dropped.

To disable timeout set value to 0.

By default client timeout is set to 5 seconds.

Source

pub fn max_conn(self, max: usize) -> Self

Sets the maximum per-worker number of concurrent connections.

All socket listeners will stop accepting connections when this limit is reached for each worker.

By default max connections is set to a 25k.

Source

pub fn max_conn_rate(self, max: usize) -> Self

Sets the maximum per-worker concurrent connection establish process.

All listeners will stop accepting connections when this limit is reached. It can be used to limit the global SSL CPU usage.

By default max connections is set to a 256.

Source

pub fn allowed_origins(self, allowed_origins: Vec<String>) -> Self

Source

pub fn allowed_methods(self, allowed_methods: Vec<Method>) -> Self

Source

pub fn route_factory<F: Fn() -> Vec<Route> + Send + Sync + 'static>( self, factory: F, ) -> Self

Set the route factory function.

This function is called once per worker to create route definitions.

Source

pub fn route_factory_arc( self, factory: Arc<dyn Fn() -> Vec<Route> + Send + Sync>, ) -> Self

Set the route factory using an existing Arc.

Useful for sharing the same factory across multiple server configurations.

Source

pub fn boot_thread<F: Fn() -> Vec<Route> + Send + Sync + 'static>( self, factory: F, ) -> Self

👎Deprecated since 0.32.0:

Use route_factory instead

Source

pub fn has_started_bootstrap(self, has_started_bootstrap: bool) -> Self

Source

pub fn body_config(self, body_config: BodyConfig) -> Self

Source

pub fn json_config(self, config: BodyConfig) -> Self

👎Deprecated since 0.31.0:

Use body_config instead

Source

pub fn custom_state_builder( self, builder: Box<dyn FnOnce() -> HashMap<String, Box<dyn Any + Send + Sync>> + Send>, ) -> Self

Source

pub fn on_shutdown<F>(self, func: F) -> Self
where F: Future<Output = ()> + Send + 'static,

Sets a custom shutdown handler to be called when the application is shutting down.

This method allows you to provide a future that will be awaited during shutdown. It is typically used to perform cleanup tasks like closing database connections, flushing logs, or other async teardown operations.

Note: If a custom shutdown_signal is also provided using [shutdown_signal], that will take precedence over this handler, and this on_shutdown handler will not be executed.

Source

pub fn shutdown_signal<F>(self, func: F) -> Self
where F: Future<Output = ()> + Send + 'static,

Sets a custom shutdown signal handler that determines when the application should begin shutting down.

This method allows you to provide a future that, when resolved, triggers the application shutdown. It is typically used to listen for signals like Ctrl+C or system termination requests (SIGTERM).

If this shutdown signal is provided, it will override any handler set using [on_shutdown].

Source

pub fn validate(&self) -> AppResult<()>

Validate the server configuration before startup.

This method checks for common configuration errors and warns about potentially problematic settings. It returns an error if critical issues are found.

§Validation Rules
  • Port must not be 0
  • Workers must be at least 1
  • Backlog must not be negative
  • Timeout values are checked for reasonable ranges (warnings only)
§Example
use foxtive_ntex::http::server::ServerConfig;
// FoxtiveSetup must be created with your application's setup logic
// let config = ServerConfig::validate_example();
Source

pub fn dev_mode(host: &str, port: u16, setup: FoxtiveSetup) -> Self

Create a server configuration with smart defaults for development.

This is a convenience method that creates a configuration optimized for local development with relaxed timeouts and single worker.

§Defaults
  • Workers: 1 (easier debugging)
  • Client timeout: 60 seconds
  • Keep-alive: 60 seconds
  • Max connections: 1000
  • Backlog: 256
§Example
use foxtive_ntex::http::server::ServerConfig;
// FoxtiveSetup must be created with your application's setup logic
// let config = ServerConfig::dev_mode("127.0.0.1", 3000, setup);
Source

pub fn production_mode(host: &str, port: u16, setup: FoxtiveSetup) -> Self

Create a server configuration optimized for production deployment.

This configuration uses conservative settings suitable for most production workloads with good performance and resource management.

§Defaults
  • Workers: Auto-detected (number of CPU cores)
  • Client timeout: 15 seconds
  • Keep-alive: 30 seconds
  • Max connections: 25,000
  • Backlog: 2048
§Example
use foxtive_ntex::http::server::ServerConfig;
// FoxtiveSetup must be created with your application's setup logic
// let config = ServerConfig::production_mode("0.0.0.0", 8080, setup);
Source

pub fn high_performance_mode(host: &str, port: u16, setup: FoxtiveSetup) -> Self

Create a server configuration optimized for high-performance scenarios.

This configuration maximizes throughput and concurrent connections, suitable for high-traffic APIs or microservices.

§Defaults
  • Workers: 2x CPU cores (for I/O-bound workloads)
  • Client timeout: 5 seconds
  • Keep-alive: 10 seconds
  • Max connections: 50,000
  • Max connection rate: 512
  • Backlog: 4096
§Warning

This configuration uses more resources. Monitor your system to ensure it can handle the increased load.

§Example
use foxtive_ntex::http::server::ServerConfig;
// FoxtiveSetup must be created with your application's setup logic
// let config = ServerConfig::high_performance_mode("0.0.0.0", 8080, setup);
Source

pub fn shutdown_config(self, config: ShutdownConfig) -> Self

Configure shutdown behavior with timeout and cleanup coordination.

This method sets up coordinated shutdown for all registered services. Services are shut down in priority order with per-service timeouts.

§Arguments
  • config - Shutdown configuration with timeout settings
§Example
use foxtive_ntex::http::server::{ServerConfig, ShutdownConfig};
// FoxtiveSetup must be created with your application's setup logic
// let config = ServerConfig::create("127.0.0.1", 8080, setup)
//     .shutdown_config(ShutdownConfig::new(30));
Source

pub fn register_shutdown_service<F, Fut>( self, name: &str, priority: u8, cleanup: F, ) -> Self
where F: FnOnce() -> Fut + Send + 'static, Fut: Future<Output = ()> + Send + 'static,

Register a service for graceful shutdown cleanup.

Services are shut down in priority order (lower priority number first). Each service has a timeout to prevent one slow service from blocking others.

§Arguments
  • name - Name of the service (for logging)
  • priority - Shutdown priority (lower = shutdown first)
    • 0-10: Critical infrastructure (databases, message queues)
    • 11-50: Application services (caches, connection pools)
    • 51-100: Auxiliary services (loggers, metrics)
  • cleanup - Async cleanup function to execute
§Example
use foxtive_ntex::http::server::ServerBuilder;
// FoxtiveSetup must be created with your application's setup logic
// let config = ServerBuilder::create("127.0.0.1", 8080, setup)
//     .register_shutdown_service("database", 1, || async {
//         println!("Database closed");
//     });
Source

pub async fn start<Callback, Fut>(self, callback: Callback) -> AppResult<()>
where Callback: FnOnce(FoxtiveNtexState) -> Fut + Copy + Send + 'static, Fut: Future<Output = AppResult<()>> + Send + 'static,

Start the HTTP server with an optional bootstrap callback.

This method validates the configuration, sets up the ntex server, and starts listening for incoming requests.

§Arguments
  • callback - Optional async function that runs after state creation but before server starts. Useful for database migrations, cache warming, etc.
§Example
use foxtive_ntex::http::server::ServerBuilder;
use foxtive::setup::FoxtiveSetup;

let foxtive = FoxtiveSetup::default();

ServerBuilder::dev_mode("127.0.0.1", 3000, foxtive)
    .on_shutdown(async {
        println!("Server shutting down gracefully");
    })
    .start(|state| async move {
        // Bootstrap code here (e.g., database migrations)
        println!("Server starting...");
        Ok(())
    })
    .await?;
Source

pub async fn run(self) -> AppResult<()>

Start the HTTP server without a bootstrap callback.

This is a convenience method for simple servers that don’t need initialization logic before starting.

§Example
use foxtive_ntex::http::server::ServerBuilder;
use foxtive::setup::FoxtiveSetup;

let foxtive = FoxtiveSetup::default();

ServerBuilder::production_mode("0.0.0.0", 8080, foxtive)
    .run()
    .await?;

Auto Trait Implementations§

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> 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<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