use std::net::SocketAddr;
use lambda_http::Error as LambdaError;
use serverust_core::App;
use tokio::net::ToSocketAddrs;
pub use aws_lambda_events;
pub use lambda_http;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Runtime {
Lambda,
Http,
}
pub fn detect_runtime(env_value: Option<&str>) -> Runtime {
match env_value {
Some(value) if !value.is_empty() => Runtime::Lambda,
_ => Runtime::Http,
}
}
fn current_runtime() -> Runtime {
detect_runtime(std::env::var("AWS_LAMBDA_RUNTIME_API").ok().as_deref())
}
pub async fn run_lambda(app: App) -> Result<(), LambdaError> {
if std::env::var_os("AWS_LAMBDA_HTTP_IGNORE_STAGE_IN_PATH").is_none() {
unsafe { std::env::set_var("AWS_LAMBDA_HTTP_IGNORE_STAGE_IN_PATH", "true") };
}
let router = app.into_router();
lambda_http::run(router).await
}
pub async fn run_http<A: ToSocketAddrs>(app: App, addr: A) -> std::io::Result<()> {
app.run_http(addr).await
}
pub async fn run(app: App) -> Result<(), LambdaError> {
match current_runtime() {
Runtime::Lambda => run_lambda(app).await,
Runtime::Http => {
let addr: SocketAddr = "0.0.0.0:3000".parse().expect("addr literal sempre parseia");
run_http(app, addr).await.map_err(LambdaError::from)
}
}
}
pub trait AppRuntime {
fn run(self) -> impl std::future::Future<Output = Result<(), LambdaError>>;
fn run_lambda(self) -> impl std::future::Future<Output = Result<(), LambdaError>>;
}
impl AppRuntime for App {
fn run(self) -> impl std::future::Future<Output = Result<(), LambdaError>> {
run(self)
}
fn run_lambda(self) -> impl std::future::Future<Output = Result<(), LambdaError>> {
run_lambda(self)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detect_runtime_returns_lambda_when_env_var_is_set() {
assert_eq!(
detect_runtime(Some("127.0.0.1:9001")),
Runtime::Lambda,
"presença da var indica execução Lambda"
);
}
#[test]
fn detect_runtime_returns_http_when_env_var_is_absent() {
assert_eq!(detect_runtime(None), Runtime::Http);
}
#[test]
fn detect_runtime_returns_http_when_env_var_is_empty() {
assert_eq!(
detect_runtime(Some("")),
Runtime::Http,
"valor vazio não deve ativar runtime Lambda"
);
}
}