use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use lambda_http::http::{HeaderName, HeaderValue, StatusCode};
use lambda_http::{RequestExt, service_fn};
use super::codes;
use super::failure::{Failure, FailureKind};
use super::policy::{Admission, AdmitAll, Policy};
use super::render::ErrorRenderer;
use super::request::{DEFAULT_BODY_LIMIT, Request};
use super::response::{HttpResponse, IntoResponse, apply_headers};
use crate::{Context, Deadline, Invocation, RuntimeError};
const RESERVE: Duration = Duration::from_millis(100);
pub type Finalizer = Box<dyn Fn(&Invocation, &mut HttpResponse) + Send + Sync>;
pub struct Api<P, R, A = AdmitAll> {
operation: &'static str,
policy: P,
renderer: R,
admission: A,
body_limit: usize,
finalize: Option<Finalizer>,
}
impl<P, R, A> std::fmt::Debug for Api<P, R, A> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Api")
.field("operation", &self.operation)
.field("body_limit", &self.body_limit)
.field("finalize", &self.finalize.is_some())
.finish_non_exhaustive()
}
}
impl<P, R> Api<P, R, AdmitAll>
where
P: Policy,
R: ErrorRenderer,
{
#[must_use]
pub fn new(operation: &'static str, policy: P, renderer: R) -> Self {
Self {
operation,
policy,
renderer,
admission: AdmitAll,
body_limit: DEFAULT_BODY_LIMIT,
finalize: None,
}
}
}
impl<P, R, A> Api<P, R, A>
where
P: Policy,
R: ErrorRenderer,
A: Admission,
{
#[must_use]
pub fn admission<B: Admission>(self, admission: B) -> Api<P, R, B> {
Api {
operation: self.operation,
policy: self.policy,
renderer: self.renderer,
admission,
body_limit: self.body_limit,
finalize: self.finalize,
}
}
#[must_use]
pub fn finalize<F>(mut self, finalize: F) -> Self
where
F: Fn(&Invocation, &mut HttpResponse) + Send + Sync + 'static,
{
self.finalize = Some(Box::new(finalize));
self
}
#[must_use]
pub fn body_limit(mut self, bytes: usize) -> Self {
self.body_limit = bytes;
self
}
pub fn operation(&self) -> &str {
self.operation
}
pub async fn handle<App, In, Out, D, H, F>(
&self,
app: Arc<App>,
request: lambda_http::Request,
decode: &D,
handler: &H,
) -> HttpResponse
where
D: Fn(&Request<'_>) -> Result<In, Failure>,
H: Fn(Arc<App>, In, Context<P::Scope>) -> F,
F: Future<Output = Result<Out, Failure>>,
Out: IntoResponse,
{
let invocation = invocation_from(&request);
#[cfg(feature = "logs")]
let span = crate::telemetry::logs::invocation_span(self.operation, &invocation);
let work = self.execute(app, &request, &invocation, decode, handler);
#[cfg(feature = "logs")]
let work = tracing::Instrument::instrument(work, span.clone());
let mut response = match work.await {
Ok(response) => response,
Err(failure) => {
self.log(&failure, &invocation);
self.renderer.render(&failure)
}
};
if let Some(finalize) = &self.finalize {
finalize(&invocation, &mut response);
}
#[cfg(feature = "otel")]
crate::telemetry::record_status(&span, response.status().as_u16());
response
}
async fn execute<App, In, Out, D, H, F>(
&self,
app: Arc<App>,
request: &lambda_http::Request,
invocation: &Invocation,
decode: &D,
handler: &H,
) -> Result<HttpResponse, Failure>
where
D: Fn(&Request<'_>) -> Result<In, Failure>,
H: Fn(Arc<App>, In, Context<P::Scope>) -> F,
F: Future<Output = Result<Out, Failure>>,
Out: IntoResponse,
{
let view = Request::new(request).with_body_limit(self.body_limit);
let deadline = invocation.deadline.with_margin(RESERVE);
let admission_headers = deadline
.run(self.admission.check(&view, invocation))
.await
.map_err(timeout_failure)?
.map_err(|failure| failure.with_kind(FailureKind::Admission))?;
let result = deadline
.run(async {
view.check_body_limit()?;
let input = decode(&view)?;
let scope = self
.policy
.authorize(&view, invocation)
.await
.map_err(|failure| failure.with_kind(FailureKind::Policy))?;
let output = handler(app, input, Context::new(invocation.clone(), scope)).await?;
output.into_response()
})
.await
.map_err(timeout_failure)
.and_then(std::convert::identity);
let mut response =
result.map_err(|failure| failure.with_headers(admission_headers.clone()))?;
let admitted: Vec<(HeaderName, HeaderValue)> = admission_headers
.iter()
.filter_map(|(name, value)| {
Some((
HeaderName::try_from(name.as_str()).ok()?,
HeaderValue::try_from(value.as_str()).ok()?,
))
})
.collect();
apply_headers(&mut response, &admitted);
Ok(response)
}
fn log(&self, failure: &Failure, invocation: &Invocation) {
#[cfg(feature = "logs")]
{
let (code, kind) = (failure.code(), failure.kind());
if failure.is_server_error() {
tracing::error!(
operation = self.operation,
request_id = %invocation.request_id,
code,
kind = ?kind,
"request failed"
);
} else {
tracing::debug!(
operation = self.operation,
request_id = %invocation.request_id,
code,
kind = ?kind,
"request refused"
);
}
}
#[cfg(not(feature = "logs"))]
{
let _ = (failure, invocation);
}
}
pub async fn run<App, In, Out, D, H, F>(
self,
app: Arc<App>,
decode: D,
handler: H,
) -> Result<(), RuntimeError>
where
App: Send + Sync + 'static,
In: Send,
D: Fn(&Request<'_>) -> Result<In, Failure> + Send + Sync,
H: Fn(Arc<App>, In, Context<P::Scope>) -> F + Send + Sync,
F: Future<Output = Result<Out, Failure>> + Send,
Out: IntoResponse,
P::Scope: Send,
{
let api = &self;
let decode = &decode;
let handler = &handler;
let service = service_fn(move |request: lambda_http::Request| {
let app = Arc::clone(&app);
async move {
Ok::<_, std::convert::Infallible>(api.handle(app, request, decode, handler).await)
}
});
lambda_http::run(service)
.await
.map_err(crate::runtime::loop_failure)
}
}
pub(super) fn timeout_failure(_error: RuntimeError) -> Failure {
Failure::new(
StatusCode::GATEWAY_TIMEOUT,
codes::TIMEOUT,
"Request deadline exceeded",
)
.with_kind(FailureKind::Deadline)
}
fn invocation_from(request: &lambda_http::Request) -> Invocation {
request.lambda_context_ref().map_or_else(
|| {
Invocation::new(
String::new(),
Deadline::after(crate::runtime::MAX_FUNCTION_TIMEOUT),
)
},
crate::runtime::invocation_from,
)
}