Skip to main content

ServerBuilder

Struct ServerBuilder 

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

Builder for configuring and launching the HTTP server.

§Example

use stateset_embedded::Commerce;
use stateset_http::ServerBuilder;

let commerce = Commerce::new(":memory:")?;

ServerBuilder::new_from_env(commerce)?
    .bind("0.0.0.0:8080".parse()?)
    .with_cors()
    .with_request_id()
    .with_bearer_auth("replace-me-with-a-secret")
    .serve()
    .await?;

Implementations§

Source§

impl ServerBuilder

Source

pub fn new(commerce: Commerce) -> Self

Create a new server builder wrapping a Commerce instance.

Source

pub fn new_from_env(commerce: Commerce) -> Result<Self, HttpError>

Create a new server builder and apply /metrics network policy from environment.

This is useful for startup wiring where operators configure network policy via:

  • STATESET_HTTP_METRICS_IP_ALLOWLIST
  • STATESET_HTTP_METRICS_IP_CIDR_ALLOWLIST
  • STATESET_HTTP_METRICS_TRUSTED_PROXIES
  • STATESET_HTTP_METRICS_FORWARDED_MAX_BYTES
  • STATESET_HTTP_METRICS_X_FORWARDED_FOR_MAX_BYTES
  • STATESET_HTTP_METRICS_X_REAL_IP_MAX_BYTES
  • STATESET_HTTP_METRICS_AUTHORIZATION_MAX_BYTES
  • STATESET_HTTP_ALLOW_UNAUTHENTICATED
Source

pub fn with_allow_unauthenticated_from_env(self) -> Result<Self, HttpError>

Apply the unauthenticated opt-out from STATESET_HTTP_ALLOW_UNAUTHENTICATED.

Accepts true/false (also 1/0, yes/no). Unset or empty leaves the secure default (false) in place.

Source

pub const fn require_idempotency_keys(self, require: bool) -> Self

Require an Idempotency-Key header on money-moving create endpoints (POST /orders, /payments, /payments/{id}/refund, /ap/payments), returning HTTP 428 (Precondition Required) when it is missing.

Defaults to true; pass false to let existing deployments opt out.

Source

pub fn with_require_idempotency_keys_from_env(self) -> Result<Self, HttpError>

Apply the required-idempotency-key opt-out from STATESET_HTTP_REQUIRE_IDEMPOTENCY_KEYS.

Accepts true/false (also 1/0, yes/no). Unset or empty leaves the secure default (true) in place.

Source

pub const fn bind(self, addr: SocketAddr) -> Self

Set the bind address.

Source

pub const fn with_cors(self) -> Self

Enable CORS middleware with explicit defaults and optional env override.

Set STATESET_HTTP_ALLOWED_ORIGINS to a comma-separated list of origins to override the localhost-only defaults.

Source

pub const fn with_request_id(self) -> Self

Enable request-ID middleware (generates UUID, propagates in headers).

Source

pub fn with_bearer_auth(self, token: impl Into<String>) -> Self

Configure bearer authentication for /api/v1/* endpoints.

Requests to API routes must include Authorization: Bearer <token>.

Source

pub fn with_metrics_bearer_auth(self, token: impl Into<String>) -> Self

Configure bearer authentication for /metrics.

Source

pub fn without_metrics_auth(self) -> Self

Disable authentication for /metrics.

Source

pub fn with_metrics_ip_allowlist<I>(self, ips: I) -> Self
where I: IntoIterator<Item = IpAddr>,

Configure a client IP allowlist for /metrics.

Source

pub fn without_metrics_ip_allowlist(self) -> Self

Disable /metrics IP allowlist checks.

Source

pub fn with_metrics_ip_cidr_allowlist<I>(self, cidrs: I) -> Self
where I: IntoIterator<Item = IpCidr>,

Configure a CIDR-based client IP allowlist for /metrics.

Source

pub fn without_metrics_ip_cidr_allowlist(self) -> Self

Disable CIDR-based /metrics IP allowlist checks.

Source

pub fn with_metrics_trusted_proxies<I>(self, cidrs: I) -> Self
where I: IntoIterator<Item = IpCidr>,

Configure trusted proxy CIDRs for /metrics.

Source

pub fn with_metrics_header_limits(self, limits: MetricsHeaderLimits) -> Self

Configure max accepted forwarding header lengths for /metrics.

Source

pub fn with_metrics_network_policy_from_env(self) -> Result<Self, HttpError>

Apply /metrics network policy from environment variables.

Supported variables (comma-separated entries):

  • STATESET_HTTP_METRICS_IP_ALLOWLIST (exact IPs)
  • STATESET_HTTP_METRICS_IP_CIDR_ALLOWLIST (CIDRs and/or IPs)
  • STATESET_HTTP_METRICS_TRUSTED_PROXIES (CIDRs and/or IPs)

If a variable is present but empty, the corresponding config is disabled.

Source

pub fn with_metrics_header_limits_from_env(self) -> Result<Self, HttpError>

Apply /metrics forwarding header limits from environment variables.

Supported variables (positive integers in bytes):

  • STATESET_HTTP_METRICS_FORWARDED_MAX_BYTES
  • STATESET_HTTP_METRICS_X_FORWARDED_FOR_MAX_BYTES
  • STATESET_HTTP_METRICS_X_REAL_IP_MAX_BYTES
  • STATESET_HTTP_METRICS_AUTHORIZATION_MAX_BYTES
Source

pub fn with_request_body_limit_from_env(self) -> Result<Self, HttpError>

Apply the request body size limit from STATESET_HTTP_MAX_BODY_BYTES.

Source

pub fn without_metrics_trusted_proxies(self) -> Self

Disable trusted proxy checks for /metrics.

Source

pub fn bind_auth_tenant(self, tenant_id: impl Into<String>) -> Self

Bind the configured bearer token to a single tenant.

Requests using this token must present the same x-tenant-id.

Source

pub fn bind_auth_actor(self, actor_id: impl Into<String>) -> Self

Bind the configured bearer token to a single actor.

When set, authenticated API requests are treated as this actor during authorization checks, and any conflicting x-actor-id header is rejected.

Source

pub fn with_bearer_auth_for_tenant( self, token: impl Into<String>, tenant_id: impl Into<String>, ) -> Self

Configure bearer authentication and bind it to a tenant in one call.

Source

pub fn with_bearer_auth_for_actor( self, token: impl Into<String>, actor_id: impl Into<String>, ) -> Self

Configure bearer authentication and bind it to an actor in one call.

Source

pub fn add_bearer_auth(self, token: impl Into<String>) -> Self

Add an additional bearer token for /api/v1/* endpoints.

This leaves the primary configured API token unchanged.

Source

pub fn add_bearer_auth_for_tenant( self, token: impl Into<String>, tenant_id: impl Into<String>, ) -> Self

Add an additional bearer token bound to a tenant.

Source

pub fn add_bearer_auth_for_actor( self, token: impl Into<String>, actor_id: impl Into<String>, ) -> Self

Add an additional bearer token bound to an actor.

Source

pub fn add_bearer_auth_for_actor_and_tenant( self, token: impl Into<String>, actor_id: impl Into<String>, tenant_id: impl Into<String>, ) -> Self

Add an additional bearer token bound to both an actor and a tenant.

Source

pub fn with_tenant_db_dir(self, base_dir: impl Into<PathBuf>) -> Self

Enable per-tenant storage using <base_dir>/<tenant>.db.

Source

pub fn with_ignore_tenant_header(self) -> Self

Ignore x-tenant-id headers when per-tenant routing is disabled.

By default such requests are rejected with 400 instead of silently being served shared data. Use this escape hatch only for deployments that intentionally front a multi-tenant proxy which handles tenant isolation upstream.

Source

pub fn with_max_tenant_dbs(self, max_tenant_dbs: usize) -> Self

Set the maximum number of lazily created tenant databases kept in-memory.

Source

pub const fn with_max_request_body_bytes( self, max_request_body_bytes: usize, ) -> Self

Set the maximum accepted request body size for extractor-based endpoints.

Source

pub fn with_authz_engine(self, engine: AuthzEngine) -> Self

Enable request authorization for /api/v1/* using a provided authz engine.

By default, authorization expects actor identity to come from actor-bound bearer tokens. If you want to trust x-actor-id request headers instead, also call Self::trust_actor_headers_for_authz.

Source

pub const fn trust_actor_headers_for_authz(self) -> Self

Explicitly trust x-actor-id request headers for authorization.

Use this only behind a trusted upstream that authenticates callers and strips or overwrites any client-supplied actor header.

Source

pub const fn allow_unauthenticated(self) -> Self

Explicitly opt out of the fail-closed authentication startup check.

By default the server refuses to start on a non-loopback bind address when no API bearer tokens are configured. Call this (or set STATESET_HTTP_ALLOW_UNAUTHENTICATED=true) to acknowledge the risk and serve unauthenticated API traffic anyway.

Source

pub const fn with_strict_authz(self) -> Self

Fail closed on authorization for unmapped API paths.

By default, /api/v1 paths that the authorization layer cannot map to a resource/action pair bypass authorization (authentication still applies). When strict mode is enabled, such requests are denied with HTTP 403 instead. Only takes effect when authorization is configured via Self::with_authz_engine.

Source

pub fn without_auth(self) -> Self

Disable API authentication (not recommended for untrusted networks).

Source

pub const fn with_rate_limit( self, requests_per_second: u64, burst_size: u64, ) -> Self

Enable global rate limiting with a token bucket.

requests_per_second controls steady-state throughput; burst_size controls how many requests can be served in a burst before throttling. Requests exceeding the limit receive HTTP 429.

Source

pub fn bearer_auth_token(&self) -> Option<&str>

Return the configured bearer token, if auth is enabled.

Source

pub fn metrics_bearer_auth_token(&self) -> Option<&str>

Return the configured bearer token for /metrics, if enabled.

Source

pub fn metrics_ip_allowlist(&self) -> Option<Vec<IpAddr>>

Return configured metrics IP allowlist entries, if any.

Source

pub fn metrics_ip_cidr_allowlist(&self) -> Option<Vec<IpCidr>>

Return configured CIDR-based metrics IP allowlist entries, if any.

Source

pub fn metrics_trusted_proxies(&self) -> Option<Vec<IpCidr>>

Return configured trusted proxy CIDRs for /metrics, if any.

Source

pub const fn metrics_header_limits(&self) -> MetricsHeaderLimits

Return configured max accepted forwarding header lengths for /metrics.

Source

pub fn build(self) -> Router

Build the axum Router without starting the server.

Useful for testing or embedding in a larger application.

Source

pub async fn serve(self) -> Result<(), HttpError>

Build the router and start serving HTTP requests.

This method will block until the server is shut down.

Trait Implementations§

Source§

impl Debug for ServerBuilder

Source§

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

Formats the value using the given formatter. 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<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

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> 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> 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 follow_redirects(self) -> FollowRedirect<Self>
where Self: Sized,

Available on crate feature follow-redirect only.
Follow redirect resposes using the Standard policy. 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, 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