use std::future::Future;
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use serde::Serialize;
use serde::de::DeserializeOwned;
use crate::{Context, Deadline, Invocation, RuntimeError};
pub use lambda_runtime::Diagnostic;
impl From<RuntimeError> for Diagnostic {
fn from(error: RuntimeError) -> Self {
let error_type = match error {
RuntimeError::Configuration(_) => "Configuration",
RuntimeError::DeadlineExceeded { .. } => "DeadlineExceeded",
RuntimeError::LimitExceeded { .. } => "LimitExceeded",
RuntimeError::Other { .. } => "Other",
};
Self {
error_type: error_type.to_owned(),
error_message: error.to_string(),
}
}
}
pub(crate) const MAX_FUNCTION_TIMEOUT: Duration = Duration::from_secs(15 * 60);
const RESERVE: Duration = Duration::from_millis(100);
pub(crate) fn loop_failure(error: lambda_runtime::Error) -> RuntimeError {
RuntimeError::Other {
context: "lambda runtime".to_owned(),
source: Some(error),
}
}
pub async fn run<App, In, Out, E, H, F>(app: Arc<App>, handler: H) -> Result<(), RuntimeError>
where
App: Send + Sync + 'static,
In: DeserializeOwned + Send,
Out: Serialize,
E: Into<Diagnostic>,
H: Fn(Arc<App>, In, Context<()>) -> F + Send + Sync,
F: Future<Output = Result<Out, E>> + Send,
{
let handler = &handler;
let service = lambda_runtime::service_fn(move |event: lambda_runtime::LambdaEvent<In>| {
let app = Arc::clone(&app);
async move {
let (payload, context) = event.into_parts();
let invocation = invocation_from(&context);
let deadline = invocation.deadline.with_margin(RESERVE);
#[cfg(feature = "logs")]
let span = crate::telemetry::logs::invocation_span("runtime", &invocation);
let work = handler(app, payload, Context::new(invocation, ()));
#[cfg(feature = "logs")]
let work = tracing::Instrument::instrument(work, span);
deadline
.run(work)
.await
.map_err(Diagnostic::from)?
.map_err(Into::<Diagnostic>::into)
}
});
lambda_runtime::Runtime::new(service)
.run()
.await
.map_err(loop_failure)
}
pub fn invocation_from(context: &lambda_runtime::Context) -> Invocation {
Invocation::new(
context.request_id.clone(),
epoch_ms_to_deadline(context.deadline),
)
.with_trace_id(context.xray_trace_id.clone())
.with_invoked_arn(
Some(context.invoked_function_arn.clone()).filter(|arn| arn.starts_with("arn:")),
)
.with_tenant_id(
context
.tenant_id
.clone()
.filter(|tenant| !tenant.is_empty()),
)
}
pub(crate) fn epoch_ms_to_deadline(deadline_ms: u64) -> Deadline {
if Duration::from_millis(deadline_ms) <= MAX_FUNCTION_TIMEOUT {
return Deadline::after(Duration::from_millis(deadline_ms));
}
let now_ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |since| since.as_millis() as u64);
Deadline::at(Instant::now() + Duration::from_millis(deadline_ms.saturating_sub(now_ms)))
}