use std::future::Future;
use std::sync::{Arc, Mutex};
use axum::body::Body;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use futures::{stream, StreamExt as _};
use proa_core::{
DataLoader, DynDataLoader, DynLoaderHandle, LoadKey, LoadRequest, NoLoader, RenderBuffer,
RenderMode, RequestContext, RequestLocation,
};
use proa_framework_core::{
finalize_route_response, finalize_route_response_stream, finalize_route_response_sync,
FrameworkBody, FrameworkError, FrameworkRequestContext, FrameworkResponse, FrameworkSendStream,
FrameworkStreamFactory, RouteFinalizeMode, RouteResponse as CoreRouteResponse,
};
use tracing::error;
use super::context::{RouteContext, ROUTE_CONTEXT};
use super::local_executor::{LocalStreamExecutor, LocalStreamPrepareError};
pub use proa_framework_core::{
drive_dyn_render, drive_dyn_send_render, DynRenderOutcome, DynSendRenderOutcome, DynWebRender,
DynWebRenderSend,
};
pub struct RouteResponse<L: DataLoader = NoLoader>(CoreRouteResponse<L>);
impl RouteResponse<NoLoader> {
pub fn ssr<T>(component: T) -> Self
where
T: proa_core::WebRenderSync<NoLoader, RenderBuffer> + Send + 'static,
{
Self(CoreRouteResponse::ssr(component))
}
pub fn ssr_async<T>(component: T) -> Self
where
T: proa_core::WebRender<NoLoader, RenderBuffer> + Send + 'static,
{
Self(CoreRouteResponse::ssr_async(component))
}
pub fn ssr_stream<T>(component: T) -> Self
where
T: proa_core::WebRender<NoLoader, RenderBuffer> + Send + 'static,
{
Self(CoreRouteResponse::ssr_stream(component))
}
pub fn ssr_async_send<T>(component: T) -> Self
where
T: proa_core::WebRenderSend<NoLoader, RenderBuffer> + Send + 'static,
{
Self(CoreRouteResponse::ssr_async_send(component))
}
pub fn ssr_stream_send<T>(component: T) -> Self
where
T: proa_core::WebRenderSend<NoLoader, RenderBuffer> + Send + 'static,
{
Self(CoreRouteResponse::ssr_stream_send(component))
}
}
impl<L: DataLoader + 'static> RouteResponse<L> {
pub fn ssr_async_with_loader<T>(component: T, loader: Arc<L>) -> Self
where
T: proa_core::WebRender<L, RenderBuffer> + Send + 'static,
{
Self(CoreRouteResponse::ssr_async_with_loader(component, loader))
}
pub fn ssr_stream_with_loader<T>(component: T, loader: Arc<L>) -> Self
where
T: proa_core::WebRender<L, RenderBuffer> + Send + 'static,
{
Self(CoreRouteResponse::ssr_stream_with_loader(component, loader))
}
pub fn ssr_async_send_with_loader<T>(component: T, loader: Arc<L>) -> Self
where
T: proa_core::WebRenderSend<L, RenderBuffer> + Send + 'static,
{
Self(CoreRouteResponse::ssr_async_send_with_loader(
component, loader,
))
}
pub fn ssr_stream_send_with_loader<T>(component: T, loader: Arc<L>) -> Self
where
T: proa_core::WebRenderSend<L, RenderBuffer> + Send + 'static,
{
Self(CoreRouteResponse::ssr_stream_send_with_loader(
component, loader,
))
}
pub fn with_head(self, config: proa_core::HeadConfig) -> Self {
Self(self.0.with_head(config))
}
pub fn without_head(self) -> Self {
Self(self.0.without_head())
}
pub fn with_loader(self, loader: Arc<L>) -> Self {
Self(self.0.with_loader(loader))
}
pub fn with_render_mode(self, render_mode: RenderMode) -> Self {
Self(self.0.with_render_mode(render_mode))
}
pub fn render_to_bytes(self) -> Result<bytes::Bytes, FrameworkError> {
self.0.render_to_bytes()
}
pub fn render_to_bytes_with_public_assets(
self,
assets: &crate::PublicAssets,
) -> Result<bytes::Bytes, FrameworkError> {
self.render_to_bytes_with_assets(assets, None)
}
pub fn render_to_bytes_with_assets(
self,
assets: &crate::PublicAssets,
rsjs: Option<&crate::RsjsAssets>,
) -> Result<bytes::Bytes, FrameworkError> {
let mut context = FrameworkRequestContext::default();
context.request.set_base_path(assets.base_path().clone());
context
.request
.set_public_asset_urls(Some(assets.render_urls()));
context
.request
.set_asset_prefix(assets.asset_prefix().map(crate::AssetPrefix::shared));
context
.request
.set_framework_assets(rsjs.map(|rsjs| rsjs.published().clone()));
self.0.render_to_bytes_with_context(&context)
}
pub fn render_to_string(self) -> Result<String, FrameworkError> {
self.0.render_to_string()
}
}
impl<L: DataLoader> From<CoreRouteResponse<L>> for RouteResponse<L> {
fn from(response: CoreRouteResponse<L>) -> Self {
Self(response)
}
}
impl RouteResponse<DynLoaderHandle> {
pub fn ssr_async_with_loader_dyn<T>(component: T, loader: Arc<dyn DynDataLoader>) -> Self
where
T: proa_core::WebRender<DynLoaderHandle, RenderBuffer> + Send + 'static,
{
Self(CoreRouteResponse::ssr_async_with_loader_dyn(
component, loader,
))
}
pub fn ssr_stream_with_loader_dyn<T>(component: T, loader: Arc<dyn DynDataLoader>) -> Self
where
T: proa_core::WebRender<DynLoaderHandle, RenderBuffer> + Send + 'static,
{
Self(CoreRouteResponse::ssr_stream_with_loader_dyn(
component, loader,
))
}
pub fn ssr_async_send_with_loader_dyn<T>(component: T, loader: Arc<dyn DynDataLoader>) -> Self
where
T: proa_core::WebRenderSend<DynLoaderHandle, RenderBuffer> + Send + 'static,
{
Self(CoreRouteResponse::ssr_async_send_with_loader_dyn(
component, loader,
))
}
pub fn ssr_stream_send_with_loader_dyn<T>(component: T, loader: Arc<dyn DynDataLoader>) -> Self
where
T: proa_core::WebRenderSend<DynLoaderHandle, RenderBuffer> + Send + 'static,
{
Self(CoreRouteResponse::ssr_stream_send_with_loader_dyn(
component, loader,
))
}
pub fn with_loader_dyn(self, loader: Arc<dyn DynDataLoader>) -> Self {
Self(self.0.with_loader_dyn(loader))
}
pub fn with_preload_keys<I>(self, preload_keys: I) -> Self
where
I: IntoIterator<Item = LoadKey>,
{
Self(self.0.with_preload_keys(preload_keys))
}
pub fn with_preload_requests<I>(self, preload_requests: I) -> Self
where
I: IntoIterator<Item = LoadRequest>,
{
Self(self.0.with_preload_requests(preload_requests))
}
}
pub(super) fn framework_response_to_axum(response: FrameworkResponse) -> Response {
let FrameworkResponse {
status,
headers,
body,
} = response;
let mut axum_response = match body {
FrameworkBody::Managed(factory) => {
let (factory, head) = proa_framework_core::managed_response::adapt(factory);
let mut response = Response::builder()
.status(status)
.body(Body::empty())
.unwrap();
response
.extensions_mut()
.insert(DeferredFrameworkStream::new(factory));
response.extensions_mut().insert(ManagedPreparedHead(head));
response
}
FrameworkBody::Full(bytes) => Response::builder()
.status(status)
.body(Body::from(bytes))
.expect("framework full response should build"),
FrameworkBody::BufferedPages(buffer) => Response::builder()
.status(status)
.body(Body::from_stream(stream::iter(
buffer.into_pages().map(Ok::<_, std::convert::Infallible>),
)))
.expect("framework buffered pages response should build"),
FrameworkBody::Stream(factory) => {
let mut response = Response::builder()
.status(status)
.body(Body::empty())
.expect("framework deferred stream response should build");
response
.extensions_mut()
.insert(DeferredFrameworkStream::new(factory));
response
}
};
*axum_response.headers_mut() = headers;
axum_response
}
#[derive(Clone)]
struct ManagedPreparedHead(proa_framework_core::managed_response::PreparedHead);
#[derive(Clone, Copy)]
pub struct ManagedPreparationTimeout(pub std::time::Duration);
#[derive(Clone)]
pub(super) struct DeferredFrameworkStream {
factory: Arc<Mutex<Option<FrameworkStreamFactory>>>,
}
impl DeferredFrameworkStream {
fn new(factory: FrameworkStreamFactory) -> Self {
Self {
factory: Arc::new(Mutex::new(Some(factory))),
}
}
fn take(&self) -> Option<FrameworkStreamFactory> {
self.factory
.lock()
.expect("deferred stream mutex poisoned")
.take()
}
}
enum StreamPrepareError {
Overloaded,
Unavailable(Arc<str>),
FirstItem(proa_framework_core::FrameworkError),
TimedOut,
}
pub(super) async fn prepare_deferred_framework_stream(
mut response: Response,
executor: LocalStreamExecutor,
) -> Response {
let Some(deferred) = response
.extensions_mut()
.remove::<DeferredFrameworkStream>()
else {
return response;
};
let Some(factory) = deferred.take() else {
error!("framework stream factory was already consumed");
return framework_response_to_axum(FrameworkResponse::plain_text(
StatusCode::INTERNAL_SERVER_ERROR,
"render error",
));
};
let readiness = response
.extensions()
.get::<ManagedPreparedHead>()
.map(|h| h.0.clone());
let prepared = if readiness.is_some() {
let deadline = response
.extensions()
.get::<ManagedPreparationTimeout>()
.map_or(std::time::Duration::from_secs(30), |v| v.0);
match tokio::time::timeout(deadline, prepare_stream(factory, &executor, readiness)).await {
Ok(result) => result,
Err(_) => Err(StreamPrepareError::TimedOut),
}
} else {
prepare_stream(factory, &executor, readiness).await
};
match prepared {
Ok(stream) => {
if let Some(prepared) = response.extensions_mut().remove::<ManagedPreparedHead>() {
let Some(decisions) = prepared.0.get() else {
return framework_response_to_axum(FrameworkResponse::plain_text(
StatusCode::INTERNAL_SERVER_ERROR,
"missing prepared response head",
));
};
if let Some(status) = decisions.status() {
*response.status_mut() = status;
}
let cache_headers = [
"cache-control",
"cdn-cache-control",
"cloudflare-cdn-cache-control",
"vercel-cdn-cache-control",
"surrogate-control",
];
let restricted_cache = cache_headers.iter().any(|name| {
response.headers().get_all(*name).iter().any(|value| {
value.to_str().map_or(true, |value| {
value.split(',').any(|directive| {
let name = directive.split('=').next().unwrap_or("").trim();
["private", "no-store", "no-cache"]
.iter()
.any(|restricted| name.eq_ignore_ascii_case(restricted))
})
})
})
});
for name in decisions.headers().keys() {
if name != http::header::SET_COOKIE && name != http::header::VARY {
response.headers_mut().remove(name);
}
}
for (name, value) in decisions.headers() {
response.headers_mut().append(name.clone(), value.clone());
}
for name in cache_headers {
if restricted_cache && decisions.headers().contains_key(name) {
response
.headers_mut()
.insert(name, http::HeaderValue::from_static("private, no-store"));
}
}
response.headers_mut().remove(http::header::CONTENT_LENGTH);
response
.headers_mut()
.remove(http::header::TRANSFER_ENCODING);
if response.status() == StatusCode::NO_CONTENT
|| response.status() == StatusCode::NOT_MODIFIED
|| response.status() == StatusCode::RESET_CONTENT
{
drop(stream);
*response.body_mut() = Body::empty();
return response;
}
if response.status().is_informational() {
drop(stream);
return framework_response_to_axum(FrameworkResponse::plain_text(
StatusCode::INTERNAL_SERVER_ERROR,
"invalid document status",
));
}
}
*response.body_mut() = Body::from_stream(stream);
response
}
Err(StreamPrepareError::TimedOut) => {
error!("managed head preparation timed out before response headers");
framework_response_to_axum(FrameworkResponse::plain_text(
StatusCode::GATEWAY_TIMEOUT,
"render timeout",
))
}
Err(StreamPrepareError::Overloaded) => {
error!("local stream executor admission limit reached");
framework_response_to_axum(FrameworkResponse::plain_text(
StatusCode::SERVICE_UNAVAILABLE,
"server busy",
))
}
Err(StreamPrepareError::Unavailable(reason)) => {
error!(%reason, "local stream executor unavailable");
framework_response_to_axum(FrameworkResponse::plain_text(
StatusCode::INTERNAL_SERVER_ERROR,
"render error",
))
}
Err(StreamPrepareError::FirstItem(err)) => {
error!(?err, "framework stream failed before response headers");
framework_response_to_axum(FrameworkResponse::plain_text(
StatusCode::INTERNAL_SERVER_ERROR,
"render error",
))
}
}
}
async fn prepare_stream(
factory: FrameworkStreamFactory,
executor: &LocalStreamExecutor,
readiness: Option<proa_framework_core::managed_response::PreparedHead>,
) -> Result<FrameworkSendStream, StreamPrepareError> {
match factory {
FrameworkStreamFactory::Send(make) => {
let mut tail = make();
match proa_framework_core::managed_response::first_or_ready(
&mut tail,
readiness.as_ref(),
)
.await
{
None => Ok(tail),
Some(Err(error)) => Err(StreamPrepareError::FirstItem(error)),
Some(Ok(first)) => Ok(Box::pin(
stream::once(std::future::ready(Ok(first))).chain(tail),
)),
}
}
FrameworkStreamFactory::Local(make) => executor
.prepare_with_head(make, readiness)
.await
.map_err(|error| match error {
LocalStreamPrepareError::Overloaded => StreamPrepareError::Overloaded,
LocalStreamPrepareError::Unavailable(reason) => {
StreamPrepareError::Unavailable(reason)
}
LocalStreamPrepareError::FirstItem(error) => StreamPrepareError::FirstItem(error),
}),
}
}
fn framework_request_context(ctx: &RouteContext) -> FrameworkRequestContext {
let request_location = ctx.current_uri().cloned().map(RequestLocation::from);
let route_params = Some(ctx.current_route_params().clone());
let mut request = RequestContext::new().with_base_path(ctx.base_path().clone());
request.set_public_asset_urls(ctx.public_asset_urls());
request.set_framework_assets(ctx.framework_assets());
request.set_asset_prefix(ctx.asset_prefix());
if let Some(method) = ctx.current_method().cloned() {
request.set_method(method);
}
request.set_headers(ctx.current_headers().clone());
if let Some(location) = request_location.clone() {
request.set_original_pathname(location.path());
request.set_location(location);
}
if let Some(params) = route_params.clone() {
request.set_route_params(params);
}
FrameworkRequestContext {
head: ctx.head_config().cloned().map(Into::into),
request,
request_location,
route_params,
render_mode: RenderMode::Static,
csp_nonce: ctx.csp_nonce().cloned(),
}
}
pub(super) fn current_framework_request_context() -> FrameworkRequestContext {
ROUTE_CONTEXT
.try_with(|ctx| framework_request_context(&ctx.borrow()))
.unwrap_or_default()
}
impl<L: DataLoader + 'static> IntoResponse for RouteResponse<L> {
fn into_response(self) -> Response {
ROUTE_CONTEXT
.try_with(|ctx| {
let (is_client_request, page_title, request) = {
let mut ctx_ref = ctx.borrow_mut();
let is_client = ctx_ref.is_client_request();
let request = framework_request_context(&ctx_ref);
let page_title = if is_client {
ctx_ref.resolve_metadata().and_then(|meta| meta.title)
} else {
None
};
(is_client, page_title, request)
};
let mode = if is_client_request {
RouteFinalizeMode::ClientPayload { page_title }
} else {
RouteFinalizeMode::Document
};
let response = self.0;
let streamed_document =
matches!(&mode, RouteFinalizeMode::Document) && response.is_streaming();
let finalized = if response.is_synchronous() {
finalize_route_response_sync(response, &request, mode)
} else if streamed_document {
finalize_route_response_stream(response, &request)
} else {
block_on_current_runtime(finalize_route_response::<L>(response, &request, mode))
};
match finalized {
Ok(response) => framework_response_to_axum(response),
Err(err) => {
error!(?err, "route finalization failed");
framework_response_to_axum(FrameworkResponse::plain_text(
StatusCode::INTERNAL_SERVER_ERROR,
"render error",
))
}
}
})
.unwrap_or_else(|_| {
error!("RouteResponse used outside of routing context");
(StatusCode::INTERNAL_SERVER_ERROR, "invalid route context").into_response()
})
}
}
pub(super) fn block_on_current_runtime<F>(fut: F) -> F::Output
where
F: Future,
{
let handle = tokio::runtime::Handle::try_current().expect(
"RouteResponse async finalization was invoked outside a tokio runtime; \
axum's tokio runtime is required to drive the future",
);
match handle.runtime_flavor() {
tokio::runtime::RuntimeFlavor::MultiThread => {
tokio::task::block_in_place(|| handle.block_on(fut))
}
_ => handle.block_on(fut),
}
}
#[cfg(test)]
mod tests {
use axum::body::to_bytes;
use http_body_util::BodyExt as _;
use super::*;
use crate::route::LocalStreamExecutorConfig;
fn unavailable_local_executor() -> LocalStreamExecutor {
LocalStreamExecutor::new(LocalStreamExecutorConfig {
worker_threads: 0,
..LocalStreamExecutorConfig::default()
})
}
#[tokio::test]
async fn send_stream_first_error_becomes_http_500() {
let framework = FrameworkResponse::send_stream(|| -> FrameworkSendStream {
Box::pin(stream::iter([Err(
proa_framework_core::FrameworkError::Invariant("first item failed"),
)]))
});
let deferred = framework_response_to_axum(framework);
let response =
prepare_deferred_framework_stream(deferred, unavailable_local_executor()).await;
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(
to_bytes(response.into_body(), usize::MAX).await.unwrap(),
"render error"
);
}
#[tokio::test]
async fn send_stream_chains_first_item_and_preserves_later_body_error() {
let framework = FrameworkResponse::send_stream(|| -> FrameworkSendStream {
Box::pin(stream::iter([
Ok(bytes::Bytes::from_static(b"first")),
Err(proa_framework_core::FrameworkError::Invariant(
"later item failed",
)),
]))
});
let deferred = framework_response_to_axum(framework);
let response =
prepare_deferred_framework_stream(deferred, unavailable_local_executor()).await;
assert_eq!(response.status(), StatusCode::OK);
let mut body = response.into_body();
let first = body
.frame()
.await
.expect("first frame")
.expect("first frame succeeds")
.into_data()
.expect("data frame");
assert_eq!(first, "first");
let error = body
.frame()
.await
.expect("later error frame")
.expect_err("later stream error must reach the body");
assert!(error.to_string().contains("later item failed"));
}
#[tokio::test]
async fn send_stream_clean_eof_keeps_status_and_empty_body() {
let framework =
FrameworkResponse::send_stream(|| -> FrameworkSendStream { Box::pin(stream::empty()) });
let deferred = framework_response_to_axum(framework);
let response =
prepare_deferred_framework_stream(deferred, unavailable_local_executor()).await;
assert_eq!(response.status(), StatusCode::OK);
assert!(to_bytes(response.into_body(), usize::MAX)
.await
.unwrap()
.is_empty());
}
}
#[cfg(test)]
#[path = "managed_response_tests.rs"]
mod managed_response_tests;