Skip to main content

ConnectionLimits

Struct ConnectionLimits 

Source
#[non_exhaustive]
pub struct ConnectionLimits { pub header_read_timeout: Option<Duration>, pub max_connection_duration: Option<Duration>, pub max_connections: usize, pub max_concurrent_streams: Option<u32>, pub max_connections_per_ip: Option<usize>, }
Expand description

Connection-level limits enforced by serve_with_limits, independent of (and in addition to) the request-level tower layers applied by this crate’s router constructors.

Constructed via ConnectionLimits::default and overridden per field; #[non_exhaustive] so new limits can be added without a breaking change.

§Examples

use std::time::Duration;
use pjson_rs::infrastructure::http::ConnectionLimits;

// Long-lived WebSocket listeners disable the connection-duration ceiling
// (see that field's docs) while keeping the other defaults.
let mut limits = ConnectionLimits::default();
limits.max_connection_duration = None;
assert_eq!(limits.header_read_timeout, Some(Duration::from_secs(10)));

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§header_read_timeout: Option<Duration>

Deadline for a client to finish sending request headers after the connection is accepted, None to disable.

Defaults to 10s. Hyper’s own default is 30s and nginx uses 60s; this crate picks 10s to cut the cost of a slowloris-style header-trickle attack roughly 6x relative to hyper’s default while remaining far above the time any real client needs to send headers.

Also gates serve_with_limits’s preface-read wait (see that function’s implementation) — setting this to None together with max_connection_duration: None lets a connection that never sends a byte hold its max_connections slot (and, if assigned one, its max_connections_per_ip slot) indefinitely; at least one of the two should normally stay Some.

§max_connection_duration: Option<Duration>

Hard ceiling on a single connection’s total lifetime, None to disable.

Defaults to 300s (5 minutes). Response payload size is bounded by MAX_FRAMES_PER_REQUEST (see domain::config::limits) together with the 10MB DefaultBodyLimit applied in apply_common_layers, which implies a real client only ever needs to sustain roughly 33 KB/s to finish reading within this window — far under any real client’s throughput and far over what a stalling client can fake.

WebSocket caveat: this is a hard deadline on the whole connection, including any upgraded protocol — it will terminate a legitimate long-lived WebSocket session just as readily as a stalling one. A listener that serves WebSocket upgrade routes should set this to None and rely on WS-level idle/ping timeouts instead; crates/pjs-demo/src/servers/websocket_streaming.rs does exactly that. In particular, if serving a router that mounts this crate’s own /pjs/ws/{session_id} upgrade route (see infrastructure::websocket), set this to None — the default 300s ceiling will otherwise kill every WebSocket session it outlives.

§max_connections: usize

Maximum number of concurrently open connections.

Defaults to 1024: conservative, overridable, and comfortably under the file-descriptor soft limit on typical deployment targets. This bounds accept-loop backpressure (how many connections are being served at once), not per-request concurrency, which is a separate concern already covered by MAX_CONCURRENT_REQUESTS in apply_common_layers.

§max_concurrent_streams: Option<u32>

Hard cap on concurrently open HTTP/2 streams per connection, None to leave hyper’s own default in place.

Defaults to Some(128). Hyper’s own default is Some(200) and is documented as explicitly unstable (“not part of the stability of hyper… encouraged to set your own limit”) — 128 sits strictly below that default while remaining far above what any legitimate browser or client needs. Combined with max_connections, this bounds the worst case at max_connections * max_concurrent_streams in-flight streams before MAX_CONCURRENT_REQUESTS (see apply_common_layers) parks the rest.

§max_connections_per_ip: Option<usize>

Hard cap on concurrently open connections from a single accept-level source IP, None to disable.

Defaults to Some(64) — 1/16th of the default max_connections pool, so at least 16 distinct source IPs are needed to fully exhaust it. All three pjs-demo servers bind 127.0.0.1, so every local connection (including load/CI test loops) shares this one budget; 64 concurrent connections from a single source is still far above realistic demo or local-test load, so this is not special-cased.

Enforced by a private WebSocketRateLimiter instance owned by serve_with_limits, independent of (and never sharing state with) any RateLimitMiddleware the router itself may apply. None disables the cap entirely — no limiter instance is constructed, no cleanup task is spawned, and no per-connection map entry is made, so a reverse-proxy deployment that sets this to None (see below) pays no cost for it.

Reverse-proxy caveat: like max_connection_duration, this is enforced at the accept level, before any HTTP request is parsed — no headers exist yet, so X-Forwarded-For/trusted-proxy configuration cannot apply here. Every connection arriving through a connection-pooling reverse proxy (nginx, a load balancer, etc.) shares that proxy’s single source IP, so this cap would apply to all of them combined rather than to each real client individually. A deployment behind such a proxy must set this to None and rely on the proxy’s own per-client limiting instead.

Trait Implementations§

Source§

impl Clone for ConnectionLimits

Source§

fn clone(&self) -> ConnectionLimits

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 ConnectionLimits

Source§

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

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

impl Default for ConnectionLimits

Source§

fn default() -> Self

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

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> 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> 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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. 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> 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 = 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