Skip to main content

FrameworkBuilder

Struct FrameworkBuilder 

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

Builder for the framework’s axum Router.

Security defaults applied by build:

  • Cross-origin protection (CSRF defense) is on for unsafe methods (everything except GET / HEAD / OPTIONS). Browser-issued cross-origin POSTs are rejected with 403 based on Sec-Fetch-Site / Origin; non-browser clients are unaffected. Disable with with_cross_origin_protection(false) or allow specific callers with with_trusted_origin.
  • Security response headers (X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Referrer-Policy: strict-origin-when-cross-origin) are stamped on every response that does not already set them; tune via with_security_headers.
  • A 30 second request timeout (DEFAULT_REQUEST_TIMEOUT) bounds response production.
  • A global request body limit of 1 MiB (DEFAULT_BODY_LIMIT_BYTES).

Opt-in hardening: with_strict_csp (nonce-based Content Security Policy), with_concurrency_limit, and with_catch_panic.

Implementations§

Source§

impl FrameworkBuilder

Source

pub fn new() -> Self

Create a builder with secure defaults.

Source

pub fn with_head(self, head: HeadConfig) -> Self

Configure reusable document head defaults once for all rendered routes. The origin/mount policy belongs to HeadConfig and is never inferred from Host.

Source

pub fn with_base_path(self, base_path: BasePath) -> Self

Set the browser-visible mount prefix for a prefix-stripping proxy. Configure from an environment variable at startup with BasePath::new(&std::env::var("PROA_BASE_PATH").unwrap_or_default())?. Incoming routes remain rooted at /. Application-authored links and redirects use app_url or cx.url explicitly.

Source

pub fn with_public_origin(self, origin: &str) -> Result<Self, DiscoveryError>

Set the public HTTP(S) origin used by discovery routes.

Supply only the scheme, host and optional port, for example https://example.com. The mount prefix comes from with_base_path. This is explicit configuration; request headers are not used to infer it.

Source

pub fn with_sitemap(self, urls: impl IntoIterator<Item = SitemapUrl>) -> Self

Serve /sitemap.xml from these entries using the builder’s final public origin and base path. Configuration order does not matter.

Entries are application-local paths or same-origin absolute URLs inside the final base path directory (checked after URL normalization). The document is validated and rendered once at startup. Do not also register a custom /sitemap.xml handler. Requires with_public_origin. Replaces any previous with_sitemap or with_sitemaps configuration.

use proa_framework_axum::{
    BasePath, FrameworkBuildError, FrameworkBuilder,
    RobotsTxt, SitemapUrl,
};
let app = FrameworkBuilder::new()
    .with_base_path(BasePath::new("/apps/demo").unwrap())
    .with_public_origin("https://example.com")?
    .with_sitemap([SitemapUrl::new("/")?, SitemapUrl::new("/pricing")?])
    .with_robots(RobotsTxt::new().disallow("/admin")?)
    .try_build()?;
Source

pub fn with_sitemaps(self, files: impl IntoIterator<Item = SitemapFile>) -> Self

Serve multiple named sitemaps at /sitemap-{id}.xml, with a sitemap index at /sitemap.xml. Robots advertises the index when enabled.

Await an application-owned async generator before calling this method: .with_sitemaps(generate_sitemaps(&db).await?). All documents are validated and rendered at startup using the final origin and base path. New database content requires regeneration/restart, or custom handlers. Requires with_public_origin. IDs must be unique; an empty set is an error. This replaces a previous with_sitemap or with_sitemaps configuration. Siblings share the index directory’s scope; limits follow the sitemap-index specification.

use proa_framework_axum::{
    DiscoveryError, FrameworkBuildError, FrameworkBuilder,
    RobotsTxt, SitemapFile, SitemapUrl,
};
async fn generate_sitemaps() -> Result<Vec<SitemapFile>, DiscoveryError> {
    // Application code can await database or CMS queries here.
    Ok(vec![
        SitemapFile::new("pages", [SitemapUrl::new("/")?])?,
        SitemapFile::new("products-0", [SitemapUrl::new("/products/1")?])?,
    ])
}
let app = FrameworkBuilder::new()
    .with_public_origin("https://example.com")?
    .with_sitemaps(generate_sitemaps().await?)
    .with_robots(RobotsTxt::new())
    .try_build()?;
Source

pub fn with_robots(self, robots: RobotsTxt) -> Self

Serve /robots.txt, prefixing root-relative application rules using the final with_base_path (it replaces any base path already set on robots). Empty and wildcard-leading rules remain unchanged; a root rule also matches the bare mount URL. If a sitemap is enabled, advertise its public URL automatically.

Crawlers still need this handler exposed at the origin root: a prefix-stripping proxy must explicitly forward origin-root /robots.txt. Do not also register a custom /robots.txt handler. Existing absolute sitemap links in robots pass through unchanged. Root routing follows RFC 9309 §2.3. Startup rejects documents exceeding Google’s 500 KiB limit.

Await an application-owned async function to generate rules from data. Generation and rendering run at startup; HTTP requests serve cached bytes. Shared user-agent groups, optional crawl delays, host, and custom directives are configured on RobotsTxt before passing it here.

use proa_framework_axum::{
    DiscoveryError, FrameworkBuildError, FrameworkBuilder, RobotsTxt,
};
use std::time::Duration;

async fn generate_robots() -> Result<RobotsTxt, DiscoveryError> {
    // Application code can await database or CMS queries here.
    Ok(RobotsTxt::new()
        .group("*")?.allow("/")?.disallow("/private/")?
        .group_agents(["Applebot", "Bingbot"])?.disallow("/admin/")?
        .crawl_delay(Duration::from_millis(1500)))
}
let app = FrameworkBuilder::new()
    .with_robots(generate_robots().await?)
    .try_build()?;

This configures the crawl-policy file, not page indexing metadata. Use cx.head_mut().robots(proa_core::Robots { .. }) in a managed head hook for page-level noindex/preview directives. Crawlers must be allowed to fetch the page to read its HTML robots tag.

Source

pub fn with_rsjs_assets(self) -> Self

Serve the linked RSJS modules under content-hashed names below /_proa/immutable/rsjs/, and link those names from every page.

ON by default. Call this only to re-enable RSJS serving after without_rsjs_assets.

Source

pub fn without_rsjs_assets(self) -> Self

Disable automatic RSJS module serving and hashed URL linking.

Use this only when an application serves its own copies of the RSJS runtime and island modules at their canonical paths (/rsjs-runtime.js and /rsjs/island/<file>.js).

Source

pub fn with_public_assets(self, assets: PublicAssets) -> Self

Supply a catalog explicitly instead of loading the one from PROA_PUBLIC_ASSETS or beside the executable. This enables cx.url("public/...") in components. Handlers can also extract axum::Extension<PublicAssets>. Load it with the same BasePath used by this builder. The catalog owns routes under /_proa/immutable and /_proa/mutable.

Source

pub fn with_body_limit(self, bytes: usize) -> Self

Override the default 1 MiB request-body size limit. Returns the builder for chaining.

ⓘ
FrameworkBuilder::new()
    .with_body_limit(4 * 1024 * 1024) // 4 MiB
    .build();
Source

pub fn with_cross_origin_protection(self, enabled: bool) -> Self

Enable or disable cross-origin protection (CSRF defense).

ON by default. The built router rejects browser-issued cross-origin unsafe requests (POST, PUT, DELETE, …) with 403 based on the Sec-Fetch-Site header, falling back to comparing Origin against Host for older browsers. Safe methods and non-browser clients (no Sec-Fetch-Site, no Origin) always pass. See csrf::CrossOriginProtectionLayer for details.

Source

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

Trust an additional origin for cross-origin unsafe requests.

origin is matched exactly against the Origin request header, so pass a serialized origin like "https://app.example.com" (scheme, host, optional port, no trailing slash).

Source

pub fn with_security_headers(self, config: SecurityHeadersConfig) -> Self

Configure the security response headers applied to every response (frame options, HSTS, CSP). See SecurityHeadersConfig for the defaults.

Source

pub fn with_strict_csp(self) -> Self

Enable a strict, nonce-based Content-Security-Policy.

OFF by default, because a strict policy has to match what the app’s own markup loads. Turning it on mints a fresh 128-bit nonce per request, applies it to every Proa-emitted script tag (rsjs seed state and runtime tags, the streaming bootstrap, and out-of-order boundary swaps), and sends:

default-src 'self'; script-src 'nonce-…' 'strict-dynamic';
style-src 'self' 'unsafe-inline'; object-src 'none';
base-uri 'self'; frame-ancestors 'none'

Note what this does not cover: raw <script> tags you write yourself still need an explicit nonce attribute (read the request nonce from cx.csp_nonce()), and inline event-handler attributes (onclick="…") never run under a nonce policy.

Use with_csp_policy to adjust directives.

Source

pub fn with_csp_policy(self, policy: CspPolicy) -> Self

Enable a nonce-based CSP with a customized policy.

ⓘ
FrameworkBuilder::new()
    .with_csp_policy(
        CspPolicy::strict()
            .with_directive("img-src", "'self' data: https://cdn.example")
            .report_only(true),
    )
    .build();

report_only(true) sends Content-Security-Policy-Report-Only, which is the safe way to roll a strict policy out on a live app: violations are reported but nothing is blocked.

Source

pub fn with_request_timeout(self, timeout: Duration) -> Self

Override the default 30 second request timeout (DEFAULT_REQUEST_TIMEOUT).

The timeout bounds producing the response; streamed bodies keep flowing after the response head is out.

Source

pub fn without_request_timeout(self) -> Self

Disable the request timeout entirely. Prefer raising the timeout over removing it; without one, a stalled handler pins its resources until the client gives up.

Source

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

Cap the number of in-flight requests across the whole router (off by default). Requests beyond max wait for a slot rather than being rejected, which keeps memory bounded under load spikes at the cost of added latency.

Source

pub fn with_catch_panic(self, enabled: bool) -> Self

Opt in to tower-http’s CatchPanicLayer (off by default).

When enabled, a panicking handler or middleware produces a plain 500 Internal Server Error response instead of aborting the connection mid-stream. Panics are still logged; this only changes what the client observes. Left off by default so deployments that prefer crash-loud semantics (panic = bug = alert via connection reset) keep them.

Source

pub fn with_local_stream_executor( self, config: LocalStreamExecutorConfig, ) -> Self

Configure the persistent executor used by local (!Send) renders, buffered or streamed.

It defaults to one worker per CPU the process may use, like Tokio’s own runtime. This is a joint server resource decision: deployments should account for these threads alongside Tokio’s worker count. Stream admission and per-response transport limits bound streamed responses; bound buffered renders with with_concurrency_limit.

Source

pub fn with_static_service(self, service: Router) -> Self

Serve application assets under /static. A configured base path also composes URL tokens in CSS and native URL operations in JS/MJS assets. Install compression outside this service so transformations see source bytes.

Source

pub fn with_dynamic_routes(self, router: Router) -> Self

Source

pub fn with_dynamic_routes_and_metadata( self, router: Router, metadata: Arc<HashMap<String, ComputedRouteMeta>>, ) -> Self

Source

pub fn build(self) -> Router

Source

pub fn try_build(self) -> Result<Router, FrameworkBuildError>

Build the router with its final base path and startup settings.

Load and mount the public asset catalog unless one was supplied explicitly: the one PROA_PUBLIC_ASSETS names, or else the one proa build bundled beside this executable. Linked RSJS modules are also served under /_proa/immutable/rsjs/ by default unless disabled with without_rsjs_assets. Invalid catalogs and discovery settings return an error. Axum’s existing duplicate-route restrictions still apply.

Trait Implementations§

Source§

impl Default for FrameworkBuilder

Source§

fn default() -> Self

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

Auto Trait Implementations§

§

impl !RefUnwindSafe for FrameworkBuilder

§

impl !UnwindSafe for FrameworkBuilder

§

impl Forget for FrameworkBuilder

§

impl Freeze for FrameworkBuilder
where *const ArcInner<str> is !null: Freeze, PhantomData<ArcInner<str>>: Freeze, *const u8 is !null: Freeze, PhantomData<u8>: Freeze, *const ArcInner<HeadUrlPolicy> is !null: Freeze, PhantomData<ArcInner<HeadUrlPolicy>>: Freeze, *const ArcInner<HeadFields> is !null: Freeze, PhantomData<ArcInner<HeadFields>>: Freeze, PhantomData<SitemapUrl>: Freeze, PhantomData<SitemapFile>: Freeze, PhantomData<RobotsGroup>: Freeze, PhantomData<String>: Freeze, *const ArcInner<PreparedCatalog> is !null: Freeze, PhantomData<ArcInner<PreparedCatalog>>: Freeze, *const ArcInner<LiveCatalog> is !null: Freeze, PhantomData<ArcInner<LiveCatalog>>: Freeze, *const ArcInner<RouterInner<()>> is !null: Freeze, PhantomData<ArcInner<RouterInner<()>>>: Freeze, *const ArcInner<HashMap<String, ComputedRouteMeta>> is !null: Freeze, PhantomData<ArcInner<HashMap<String, ComputedRouteMeta>>>: Freeze, *const LeafNode<Cow<'static, str>, String> is !null: Freeze, PhantomData<(Owned, LeafOrInternal)>: Freeze, PhantomData<Box<(Cow<'static, str>, String)>>: Freeze, *const LeafNode<Cow<'static, str>, SetValZST> is !null: Freeze, PhantomData<Box<(Cow<'static, str>, SetValZST)>>: Freeze,

§

impl Move for FrameworkBuilder

§

impl Send for FrameworkBuilder
where Arc<str>: Send, RawVecInner: Send, Arc<HeadUrlPolicy>: Send, Arc<HeadFields>: Send, Arc<PreparedCatalog>: Send, Arc<LiveCatalog>: Send, Arc<RouterInner<()>>: Send, Arc<HashMap<String, ComputedRouteMeta>>: Send, NodeRef<Owned, Cow<'static, str>, String, LeafOrInternal>: Send, BoxRaw<(Cow<'static, str>, String)>: Send, NodeRef<Owned, Cow<'static, str>, SetValZST, LeafOrInternal>: Send, BoxRaw<(Cow<'static, str>, SetValZST)>: Send,

§

impl Sync for FrameworkBuilder
where Arc<str>: Sync, RawVecInner: Sync, Arc<HeadUrlPolicy>: Sync, Arc<HeadFields>: Sync, Arc<PreparedCatalog>: Sync, Arc<LiveCatalog>: Sync, Arc<RouterInner<()>>: Sync, Arc<HashMap<String, ComputedRouteMeta>>: Sync, NodeRef<Owned, Cow<'static, str>, String, LeafOrInternal>: Sync, BoxRaw<(Cow<'static, str>, String)>: Sync, NodeRef<Owned, Cow<'static, str>, SetValZST, LeafOrInternal>: Sync, BoxRaw<(Cow<'static, str>, SetValZST)>: Sync,

§

impl Unpin for FrameworkBuilder
where Arc<str>: Unpin, *const u8 is !null: Unpin, Arc<HeadUrlPolicy>: Unpin, Arc<HeadFields>: Unpin, Arc<PreparedCatalog>: Unpin, Arc<LiveCatalog>: Unpin, Arc<RouterInner<()>>: Unpin, Arc<HashMap<String, ComputedRouteMeta>>: Unpin, *const LeafNode<Cow<'static, str>, String> is !null: Unpin, Box<(Cow<'static, str>, String)>: Unpin, *const LeafNode<Cow<'static, str>, SetValZST> is !null: Unpin, Box<(Cow<'static, str>, SetValZST)>: Unpin,

§

impl UnsafeUnpin for FrameworkBuilder
where *const ArcInner<str> is !null: UnsafeUnpin, PhantomData<ArcInner<str>>: UnsafeUnpin, *const u8 is !null: UnsafeUnpin, PhantomData<u8>: UnsafeUnpin, *const ArcInner<HeadUrlPolicy> is !null: UnsafeUnpin, PhantomData<ArcInner<HeadUrlPolicy>>: UnsafeUnpin, *const ArcInner<HeadFields> is !null: UnsafeUnpin, PhantomData<ArcInner<HeadFields>>: UnsafeUnpin, PhantomData<SitemapUrl>: UnsafeUnpin, PhantomData<SitemapFile>: UnsafeUnpin, PhantomData<RobotsGroup>: UnsafeUnpin, PhantomData<String>: UnsafeUnpin, *const ArcInner<PreparedCatalog> is !null: UnsafeUnpin, PhantomData<ArcInner<PreparedCatalog>>: UnsafeUnpin, *const ArcInner<LiveCatalog> is !null: UnsafeUnpin, PhantomData<ArcInner<LiveCatalog>>: UnsafeUnpin, *const ArcInner<RouterInner<()>> is !null: UnsafeUnpin, PhantomData<ArcInner<RouterInner<()>>>: UnsafeUnpin, *const ArcInner<HashMap<String, ComputedRouteMeta>> is !null: UnsafeUnpin, PhantomData<ArcInner<HashMap<String, ComputedRouteMeta>>>: UnsafeUnpin, *const LeafNode<Cow<'static, str>, String> is !null: UnsafeUnpin, PhantomData<(Owned, LeafOrInternal)>: UnsafeUnpin, PhantomData<Box<(Cow<'static, str>, String)>>: UnsafeUnpin, *const LeafNode<Cow<'static, str>, SetValZST> is !null: UnsafeUnpin, PhantomData<Box<(Cow<'static, str>, SetValZST)>>: UnsafeUnpin,

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> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<'a, T> FromIn<'a, T> for T

Source§

fn from_in(t: T, _: &'a Allocator) -> T

Converts to this type from the input type within the given allocator.
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<'a, T, U> IntoIn<'a, U> for T
where U: FromIn<'a, T>,

Source§

fn into_in(self, allocator: &'a Allocator) -> U

Converts this type into the (usually inferred) input type within the given allocator.
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 = !

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