use std::future::Future;
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use crate::{Context, Invocation, RuntimeError};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Disposition {
Delete,
Retry,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Delivery {
pub message_id: String,
pub receipt_handle: String,
pub body: String,
#[serde(default)]
pub attributes: std::collections::HashMap<String, String>,
#[serde(default, rename = "eventSourceARN")]
pub event_source_arn: Option<String>,
}
impl Delivery {
pub fn receive_count(&self) -> u32 {
self.attributes
.get("ApproximateReceiveCount")
.and_then(|value| value.parse().ok())
.unwrap_or(1)
}
pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T, RuntimeError> {
serde_json::from_str(&self.body).map_err(|error| {
RuntimeError::other(format!("decoding message {}", self.message_id), error)
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[non_exhaustive]
pub struct Batch {
#[serde(rename = "Records")]
pub records: Vec<Delivery>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct BatchResponse {
pub batch_item_failures: Vec<ItemFailure>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ItemFailure {
pub item_identifier: String,
}
impl BatchResponse {
pub fn fail(&mut self, message_id: impl Into<String>) {
self.batch_item_failures.push(ItemFailure {
item_identifier: message_id.into(),
});
}
}
pub async fn run<App, E, H, F>(app: Arc<App>, handler: H) -> Result<(), RuntimeError>
where
App: Send + Sync + 'static,
E: std::fmt::Display,
H: Fn(Arc<App>, Delivery, Context<()>) -> F + Send + Sync,
F: Future<Output = Result<Disposition, E>> + Send,
{
let handler = &handler;
let service = lambda_runtime::service_fn(move |event: lambda_runtime::LambdaEvent<Batch>| {
let app = Arc::clone(&app);
async move {
let (batch, context) = event.into_parts();
let invocation = crate::runtime::invocation_from(&context);
let work = process(app, batch, &invocation, handler);
#[cfg(feature = "logs")]
let work = tracing::Instrument::instrument(
work,
crate::telemetry::logs::invocation_span("queue", &invocation),
);
Ok::<_, lambda_runtime::Error>(work.await)
}
});
lambda_runtime::Runtime::new(service)
.run()
.await
.map_err(crate::runtime::loop_failure)
}
pub async fn process<App, E, H, F>(
app: Arc<App>,
batch: Batch,
invocation: &Invocation,
handler: &H,
) -> BatchResponse
where
E: std::fmt::Display,
H: Fn(Arc<App>, Delivery, Context<()>) -> F,
F: Future<Output = Result<Disposition, E>>,
{
let mut response = BatchResponse::default();
let deadline = invocation
.deadline
.with_margin(std::time::Duration::from_millis(100));
let mut records = batch.records.into_iter();
for delivery in records.by_ref() {
if deadline.is_expired() {
response.fail(delivery.message_id);
break;
}
let message_id = delivery.message_id.clone();
let fifo = delivery
.event_source_arn
.as_deref()
.is_some_and(|arn| arn.ends_with(".fifo"));
let context = Context::new(invocation.clone(), ());
match deadline
.run(handler(Arc::clone(&app), delivery, context))
.await
{
Ok(Ok(Disposition::Delete)) => {}
Ok(Ok(Disposition::Retry)) => {
response.fail(message_id);
if fifo {
break;
}
}
Ok(Err(_error)) => {
#[cfg(feature = "logs")]
tracing::error!(message_id = %message_id, "message failed");
response.fail(message_id);
if fifo {
break;
}
}
Err(_) => {
response.fail(message_id);
break;
}
}
}
for skipped in records {
response.fail(skipped.message_id);
}
response
}
#[cfg(feature = "queue-visibility")]
mod visibility {
use std::time::Duration;
use aws_sdk_sqs::Client;
use super::Delivery;
use crate::RuntimeError;
pub const MAX_VISIBILITY_TIMEOUT: Duration = Duration::from_secs(12 * 60 * 60);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Visibility {
queue_url: String,
receipt_handle: String,
}
impl Visibility {
#[must_use]
pub fn new(queue_url: impl Into<String>, delivery: &Delivery) -> Self {
Self {
queue_url: queue_url.into(),
receipt_handle: delivery.receipt_handle.clone(),
}
}
pub async fn set(&self, client: &Client, delay: Duration) -> Result<(), RuntimeError> {
if delay > MAX_VISIBILITY_TIMEOUT {
return Err(RuntimeError::Configuration(format!(
"a visibility timeout of {delay:?} is above the 12-hour maximum"
)));
}
let seconds = delay.as_secs() + u64::from(delay.subsec_nanos() > 0);
client
.change_message_visibility()
.queue_url(&self.queue_url)
.receipt_handle(&self.receipt_handle)
.visibility_timeout(seconds as i32)
.send()
.await
.map(|_| ())
.map_err(|error| RuntimeError::other("changing message visibility", error))
}
}
}
#[cfg(feature = "queue-visibility")]
pub use visibility::{MAX_VISIBILITY_TIMEOUT, Visibility};