Skip to main content

ServerConfig

Struct ServerConfig 

Source
pub struct ServerConfig {
    pub host: String,
    pub port: u16,
    pub workers: Option<usize>,
    pub request_timeout: Option<Duration>,
    pub max_body_size: usize,
    pub max_connections: Option<usize>,
    pub max_concurrent_requests: Option<usize>,
    pub shutdown_timeout: Duration,
    pub header_read_timeout: Duration,
    pub tcp_nodelay: bool,
    pub connect_info: bool,
}
Expand description

Configuration for the HTTP server.

Fields are public for reading; the same-named builder methods consume and return the config for fluent construction:

use std::time::Duration;
use kerniq_core::ServerConfig;

let config = ServerConfig::new()
    .host("0.0.0.0")
    .port(3000)
    .workers(4)
    .request_timeout(Duration::from_secs(30))
    .max_body_size(10 * 1024 * 1024);

assert_eq!(config.address(), "0.0.0.0:3000");
assert_eq!(config.workers, Some(4));

Fields§

§host: String

Interface to bind to. Default: 127.0.0.1.

§port: u16

Port to bind to. 0 selects an ephemeral port. Default: 3000.

§workers: Option<usize>

Tokio worker threads used by run_blocking. Default: one per CPU core.

§request_timeout: Option<Duration>

Maximum time to produce a response. Exceeding it yields 408 REQUEST_TIMEOUT. Default: no timeout.

§max_body_size: usize

Maximum request body size in bytes accepted by body extractors (Json, String, Bytes, …). Larger bodies yield 413 PAYLOAD_TOO_LARGE. Default: 2 MiB.

§max_connections: Option<usize>

Maximum number of open TCP connections. Default: unlimited.

§max_concurrent_requests: Option<usize>

Maximum number of requests processed concurrently. Default: unlimited.

§shutdown_timeout: Duration

How long graceful shutdown waits for in-flight requests and background tasks before giving up. Default: 30 seconds.

§header_read_timeout: Duration

Maximum time for a client to send the request headers (protects against slow-header attacks). 0 disables it, which removes a per-request timer (a few percent of throughput on trivial endpoints) at the cost of that protection. Default: 30 seconds.

§tcp_nodelay: bool

Disable Nagle’s algorithm on accepted sockets. Default: true.

§connect_info: bool

Make the peer address available to handlers through ConnectInfo<SocketAddr>. Costs one small allocation per request. Default: true.

Implementations§

Source§

impl ServerConfig

Source

pub fn new() -> ServerConfig

Creates a configuration with default values.

Source

pub fn host(self, host: impl Into<String>) -> ServerConfig

Sets the interface to bind to.

Source

pub fn port(self, port: u16) -> ServerConfig

Sets the port to bind to.

Source

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

Sets the number of Tokio worker threads used by run_blocking.

Source

pub fn request_timeout(self, timeout: Duration) -> ServerConfig

Sets the per-request timeout.

Source

pub fn max_body_size(self, bytes: usize) -> ServerConfig

Sets the maximum request body size in bytes.

Source

pub fn max_connections(self, max: usize) -> ServerConfig

Limits the number of open TCP connections.

Source

pub fn max_concurrent_requests(self, max: usize) -> ServerConfig

Limits the number of requests processed concurrently.

Source

pub fn shutdown_timeout(self, timeout: Duration) -> ServerConfig

Sets the graceful shutdown timeout.

Source

pub fn header_read_timeout(self, timeout: Duration) -> ServerConfig

Sets the request header read timeout (Duration::ZERO disables it).

Source

pub fn tcp_nodelay(self, enabled: bool) -> ServerConfig

Enables or disables TCP_NODELAY.

Source

pub fn connect_info(self, enabled: bool) -> ServerConfig

Enables or disables ConnectInfo<SocketAddr> for handlers.

Source

pub fn address(&self) -> String

The host:port address, with brackets around IPv6 hosts.

Source

pub fn from_env() -> Result<ServerConfig, ConfigError>

Builds a configuration from defaults overridden by KERNIQ_* environment variables. See ServerConfig::apply_env_vars.

Source

pub fn apply_env(self) -> Result<ServerConfig, ConfigError>

Overrides values from the process environment. See ServerConfig::apply_env_vars.

Source

pub fn apply_env_vars<I, K, V>( self, vars: I, ) -> Result<ServerConfig, ConfigError>
where I: IntoIterator<Item = (K, V)>, K: AsRef<str>, V: AsRef<str>,

Overrides values from the given (name, value) pairs, using these variables (durations are in seconds, sizes in bytes):

VariableSetting
KERNIQ_HOSThost
KERNIQ_PORTport
KERNIQ_WORKERSworkers
KERNIQ_REQUEST_TIMEOUTrequest_timeout
KERNIQ_MAX_BODY_SIZEmax_body_size
KERNIQ_MAX_CONNECTIONSmax_connections
KERNIQ_MAX_CONCURRENT_REQUESTSmax_concurrent_requests
KERNIQ_SHUTDOWN_TIMEOUTshutdown_timeout
KERNIQ_HEADER_READ_TIMEOUTheader_read_timeout
KERNIQ_TCP_NODELAYtcp_nodelay
KERNIQ_CONNECT_INFOconnect_info

Unrelated variables are ignored. The result is validated.

Source

pub fn from_file(path: impl AsRef<Path>) -> Result<ServerConfig, ConfigError>

Available on crate feature config-file only.

Loads a configuration from a TOML file. Missing keys use defaults; unknown keys are rejected. Durations are given in seconds.

host = "0.0.0.0"
port = 8080
request_timeout = 30
max_concurrent_requests = 1024
Source

pub fn from_toml_str(text: &str) -> Result<ServerConfig, ConfigError>

Available on crate feature config-file only.

Parses a configuration from a TOML string. See ServerConfig::from_file.

Source

pub fn validate(&self) -> Result<(), ConfigError>

Checks that values are within range.

Trait Implementations§

Source§

impl Clone for ServerConfig

Source§

fn clone(&self) -> ServerConfig

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ServerConfig

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for ServerConfig

Source§

fn default() -> ServerConfig

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for ServerConfig

Source§

fn deserialize<__D>( __deserializer: __D, ) -> Result<ServerConfig, <__D as Deserializer<'de>>::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Eq for ServerConfig

Source§

impl From<&ServerConfig> for ServeOptions

Source§

fn from(config: &ServerConfig) -> ServeOptions

Converts to this type from the input type.
Source§

impl PartialEq for ServerConfig

Source§

fn eq(&self, other: &ServerConfig) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Serialize for ServerConfig

Source§

fn serialize<__S>( &self, __serializer: __S, ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for ServerConfig

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self> ⓘ

Attaches the current Context to this type, returning a WithContext wrapper. Read more
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> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<L> LayerExt<L> for L

Source§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in Layered.
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ServiceExt for T

Source§

fn compression(self) -> Compression<Self>
where Self: Sized,

Available on crate features compression-br or compression-deflate or compression-gzip or compression-zstd only.
Compresses response bodies. Read more
Source§

fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>
where Self: Sized,

Available on crate feature trace only.
High level tracing that classifies responses using HTTP status codes. Read more
Source§

fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>
where Self: Sized,

Available on crate feature trace only.
High level tracing that classifies responses using gRPC headers. Read more
Source§

fn set_request_id<M>( self, header_name: HeaderName, make_request_id: M, ) -> SetRequestId<Self, M>
where Self: Sized, M: MakeRequestId,

Available on crate feature request-id only.
Add request id header and extension. Read more
Source§

fn set_x_request_id<M>(self, make_request_id: M) -> SetRequestId<Self, M>
where Self: Sized, M: MakeRequestId,

Available on crate feature request-id only.
Add request id header and extension, using x-request-id as the header name. Read more
Source§

fn propagate_request_id( self, header_name: HeaderName, ) -> PropagateRequestId<Self>
where Self: Sized,

Available on crate feature request-id only.
Propgate request ids from requests to responses. Read more
Source§

fn propagate_x_request_id(self) -> PropagateRequestId<Self>
where Self: Sized,

Available on crate feature request-id only.
Propgate request ids from requests to responses, using x-request-id as the header name. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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