Skip to main content

TcpServer

Struct TcpServer 

Source
pub struct TcpServer { /* private fields */ }
Expand description

TCP server with asupersync integration.

This server manages the lifecycle of connections and requests using asupersync’s structured concurrency primitives. Each connection runs in its own region, and each request gets its own task with a budget.

Implementations§

Source§

impl TcpServer

Source

pub fn new(config: ServerConfig) -> Self

Creates a new TCP server with the given configuration.

Source

pub fn config(&self) -> &ServerConfig

Returns the server configuration.

Source

pub fn current_connections(&self) -> u64

Returns the current number of active connections.

Source

pub fn metrics(&self) -> ServerMetrics

Returns a snapshot of the server’s connection pool metrics.

Source

pub fn is_draining(&self) -> bool

Returns true if the server is draining (shutting down gracefully).

Source

pub fn start_drain(&self)

Starts the drain process for graceful shutdown.

This sets the draining flag, which causes the server to:

  • Stop accepting new connections
  • Return 503 to new connection attempts
  • Allow in-flight requests to complete
Source

pub async fn wait_for_drain( &self, timeout: Duration, poll_interval: Option<Duration>, ) -> bool

Waits for all in-flight connections to drain, with a timeout.

Returns true if all connections drained successfully, false if the timeout was reached with connections still active.

§Arguments
  • timeout - Maximum time to wait for connections to drain
  • poll_interval - How often to check connection count (default 10ms)
Source

pub async fn drain(&self) -> u64

Initiates graceful shutdown and waits for connections to drain.

This is a convenience method that combines start_drain() and wait_for_drain() using the configured drain timeout.

Returns the number of connections that were forcefully closed (0 if all drained within the timeout).

Source

pub fn shutdown_controller(&self) -> &Arc<ShutdownController>

Returns a reference to the server’s shutdown controller.

This can be used to coordinate shutdown from external code, such as signal handlers or health check endpoints.

Source

pub fn subscribe_shutdown(&self) -> ShutdownReceiver

Returns a receiver for shutdown notifications.

Use this to receive shutdown signals in other parts of your application. Multiple receivers can be created and they will all be notified.

Source

pub fn shutdown(&self)

Initiates server shutdown.

This triggers the shutdown process:

  1. Sets the draining flag to stop accepting new connections
  2. Notifies all shutdown receivers
  3. The server’s accept loop will exit and drain connections

This method is safe to call multiple times - subsequent calls are no-ops.

Source

pub fn is_shutting_down(&self) -> bool

Checks if shutdown has been initiated.

Source

pub async fn serve_with_shutdown<H, Fut>( &self, cx: &Cx, shutdown: ShutdownReceiver, handler: H, ) -> Result<GracefulOutcome<()>, ServerError>
where H: Fn(RequestContext, &mut Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Response> + Send + 'static,

Runs the server with graceful shutdown support.

The server will run until either:

  • The provided shutdown receiver signals shutdown
  • The server Cx is cancelled
  • An unrecoverable error occurs

When shutdown is signaled, the server will:

  1. Stop accepting new connections
  2. Wait for existing connections to complete (up to drain_timeout)
  3. Return gracefully
§Example
use asupersync::signal::ShutdownController;
use fastapi_http::{TcpServer, ServerConfig};

let controller = ShutdownController::new();
let server = TcpServer::new(ServerConfig::new("127.0.0.1:8080"));

// Get a shutdown receiver
let shutdown = controller.subscribe();

// In another task, you can trigger shutdown:
// controller.shutdown();

server.serve_with_shutdown(&cx, shutdown, handler).await?;
Source

pub async fn serve<H, Fut>( &self, cx: &Cx, handler: H, ) -> Result<(), ServerError>
where H: Fn(RequestContext, &mut Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Response> + Send + 'static,

Runs the server, accepting connections and handling requests.

This method will run until the server Cx is cancelled or an unrecoverable error occurs.

§Arguments
  • cx - The capability context for the server region
  • handler - The request handler function
§Errors

Returns an error if binding fails or an unrecoverable IO error occurs.

Source

pub async fn serve_on<H, Fut>( &self, cx: &Cx, listener: TcpListener, handler: H, ) -> Result<(), ServerError>
where H: Fn(RequestContext, &mut Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Response> + Send + 'static,

Runs the server on a specific listener.

This is useful when you already have a bound listener.

Source

pub async fn serve_handler( &self, cx: &Cx, handler: Arc<dyn Handler>, ) -> Result<(), ServerError>

Runs the server with a Handler trait object.

This is the recommended way to serve an application that implements the Handler trait (like App).

§Example
use fastapi_http::TcpServer;
use fastapi_core::{App, Handler};
use std::sync::Arc;

let app = App::builder()
    .get("/", handler_fn)
    .build();

let server = TcpServer::new(ServerConfig::new("127.0.0.1:8080"));
let cx = Cx::for_testing();
server.serve_handler(&cx, Arc::new(app)).await?;
Source

pub async fn serve_on_handler( &self, cx: &Cx, listener: TcpListener, handler: Arc<dyn Handler>, ) -> Result<(), ServerError>

Runs the server on a specific listener with a Handler trait object.

Source

pub async fn serve_concurrent<H, Fut>( &self, cx: &Cx, scope: &Scope<'_>, state: &mut RuntimeState, handler: H, ) -> Result<(), ServerError>
where H: Fn(RequestContext, &mut Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Response> + Send + 'static,

Serves HTTP requests with concurrent connection handling using asupersync Scope.

This method uses Scope::spawn_registered for proper structured concurrency, ensuring all spawned connection tasks are tracked and can be properly drained during shutdown.

§Arguments
  • cx - The asupersync context for cancellation and tracing
  • scope - A scope for spawning connection tasks
  • state - Runtime state for task registration
  • handler - The request handler

Trait Implementations§

Source§

impl Debug for TcpServer

Source§

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

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

impl Default for TcpServer

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<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: NoopSpan) -> Self

Instruments this future with a span (no-op when disabled).
Source§

fn in_current_span(self) -> Self

Instruments this future with the current span (no-op when disabled).
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
Source§

impl<T> ResponseProduces<T> for T