From 41c8033838f22a8a44aea090d0b13480a86af8af Mon Sep 17 00:00:00 2001 From: sundaresanr Date: Thu, 19 Nov 2026 22:49:34 -0800 Subject: [PATCH] feat(aws_s3 source): extend the visibility timeout of messages in process A message goes back on the queue when its visibility timeout ends, even if a poller still processes it. A message that lists many objects can take longer than any fixed timeout, so another poller reads it again and the objects are delivered twice. A long timeout avoids this, but it also hides the message for that long after a restart. Add the `extend_visibility_timeout` SQS setting. When it is on, a poller extends the visibility timeout of the messages it holds each time half of the timeout has passed, and stops before it deletes them. The default of false keeps the current behavior. --- src/internal_events/aws_sqs.rs | 57 +++++++++++++++++ src/sources/aws_s3/mod.rs | 61 ++++++++++++++++++ src/sources/aws_s3/sqs.rs | 114 ++++++++++++++++++++++++++++++++- 3 files changed, 230 insertions(+), 2 deletions(-) diff --git a/src/internal_events/aws_sqs.rs b/src/internal_events/aws_sqs.rs index b0c14493ea57a..20c1c0a414b3f 100644 --- a/src/internal_events/aws_sqs.rs +++ b/src/internal_events/aws_sqs.rs @@ -179,6 +179,63 @@ mod s3 { } } + #[derive(Debug, NamedInternalEvent)] + pub struct SqsMessageVisibilityExtendPartialError { + pub entries: Vec, + } + + impl InternalEvent for SqsMessageVisibilityExtendPartialError { + fn emit(self) { + error!( + message = "Extension of SQS message visibility timeout failed.", + message_ids = %self.entries.iter() + .map(|x| format!("{}/{}", x.id, x.code)) + .collect::>() + .join(", "), + error_code = "failed_extending_some_sqs_message_visibility", + error_type = error_type::REQUEST_FAILED, + stage = error_stage::PROCESSING, + ); + counter!( + "component_errors_total", + "error_code" => "failed_extending_some_sqs_message_visibility", + "error_type" => error_type::REQUEST_FAILED, + "stage" => error_stage::PROCESSING, + ) + .increment(1); + } + } + + #[derive(Debug, NamedInternalEvent)] + pub struct SqsMessageVisibilityExtendBatchError { + pub count: usize, + pub error: E, + } + + impl InternalEvent + for SqsMessageVisibilityExtendBatchError + { + fn emit(self) { + error!( + message = "Extension of SQS message visibility timeout failed.", + count = self.count, + error = %self.error, + aws_error_code = self.error.code().unwrap_or("unknown"), + aws_error_message = self.error.message().unwrap_or(""), + error_code = "failed_extending_all_sqs_message_visibility", + error_type = error_type::REQUEST_FAILED, + stage = error_stage::PROCESSING, + ); + counter!( + "component_errors_total", + "error_code" => "failed_extending_all_sqs_message_visibility", + "error_type" => error_type::REQUEST_FAILED, + "stage" => error_stage::PROCESSING, + ) + .increment(1); + } + } + #[derive(Debug, NamedInternalEvent)] pub struct SqsMessageSentSucceeded { pub message_ids: Vec, diff --git a/src/sources/aws_s3/mod.rs b/src/sources/aws_s3/mod.rs index 493b6d889b95c..b6e35d02a82d3 100644 --- a/src/sources/aws_s3/mod.rs +++ b/src/sources/aws_s3/mod.rs @@ -832,6 +832,67 @@ mod integration_tests { .await; } + #[tokio::test] + async fn s3_extends_visibility_timeout_while_processing() { + trace_init(); + + let s3 = s3_client().await; + let sqs = sqs_client().await; + let queue = create_queue(&sqs).await; + let bucket = create_bucket(&s3).await; + + let key = "data/part-00000.txt"; + let lines: Vec = random_lines(100).take(10).collect(); + s3.put_object() + .bucket(bucket.clone()) + .key(key) + .body(ByteStream::from(lines.join("\n").into_bytes())) + .send() + .await + .expect("Could not put object"); + let body = serde_json::json!({ + "Records": [{ + "eventVersion": "2.1", + "eventSource": "aws:s3", + "awsRegion": "us-east-1", + "eventTime": "2022-03-24T19:43:00.548Z", + "eventName": "ObjectCreated:Put", + "s3": { "bucket": { "name": bucket }, "object": { "key": key } }, + }] + }); + sqs.send_message() + .queue_url(queue.clone()) + .message_body(body.to_string()) + .send() + .await + .unwrap(); + + let mut config = config(&queue, None, false, DeserializerConfig::Bytes); + let sqs_config = config.sqs.as_mut().unwrap(); + sqs_config.client_concurrency = std::num::NonZeroUsize::new(1); + sqs_config.visibility_timeout_secs = 2; + sqs_config.extend_visibility_timeout = true; + + // This sender does not acknowledge the events, so the source waits until they are dropped. + let (tx, rx) = SourceSender::new_test(); + let cx = SourceContext::new_test(tx, None); + let source = config.build(cx).await.unwrap(); + tokio::spawn(async move { source.await.unwrap() }); + + let events = collect_n(rx, lines.len()).await; + + // Without the extension, the message is visible again 2 seconds after the receive. + for _ in 0..4 { + tokio::time::sleep(Duration::from_secs(2)).await; + assert_eq!(count_messages(&sqs, &queue, 0).await, 0); + } + + // Dropping the events acknowledges them, and the source deletes the message. + drop(events); + tokio::time::sleep(Duration::from_secs(5)).await; + assert_eq!(count_messages(&sqs, &queue, 0).await, 0); + } + // Puts 4 objects, sends one message that lists all of them, and reads it with // `object_concurrency_per_message = 4`. async fn test_multi_object_message( diff --git a/src/sources/aws_s3/sqs.rs b/src/sources/aws_s3/sqs.rs index cdf46d8bad566..b30871cfa94d9 100644 --- a/src/sources/aws_s3/sqs.rs +++ b/src/sources/aws_s3/sqs.rs @@ -11,11 +11,15 @@ use aws_sdk_s3::{Client as S3Client, operation::get_object::GetObjectError}; use aws_sdk_sqs::{ Client as SqsClient, operation::{ + change_message_visibility_batch::ChangeMessageVisibilityBatchError, delete_message_batch::{DeleteMessageBatchError, DeleteMessageBatchOutput}, receive_message::ReceiveMessageError, send_message_batch::{SendMessageBatchError, SendMessageBatchOutput}, }, - types::{DeleteMessageBatchRequestEntry, Message, SendMessageBatchRequestEntry}, + types::{ + ChangeMessageVisibilityBatchRequestEntry, DeleteMessageBatchRequestEntry, Message, + SendMessageBatchRequestEntry, + }, }; use aws_smithy_runtime_api::client::{orchestrator::HttpResponse, result::SdkError}; use aws_types::region::Region; @@ -53,7 +57,9 @@ use crate::{ SqsMessageDeleteBatchError, SqsMessageDeletePartialError, SqsMessageDeleteSucceeded, SqsMessageProcessingError, SqsMessageProcessingSucceeded, SqsMessageReceiveError, SqsMessageReceiveSucceeded, SqsMessageSendBatchError, SqsMessageSentPartialError, - SqsMessageSentSucceeded, SqsS3EventRecordInvalidEventIgnored, StreamClosedError, + SqsMessageSentSucceeded, SqsMessageVisibilityExtendBatchError, + SqsMessageVisibilityExtendPartialError, SqsS3EventRecordInvalidEventIgnored, + StreamClosedError, }, line_agg::{self, LineAgg}, shutdown::ShutdownSignal, @@ -131,6 +137,17 @@ pub(super) struct Config { #[configurable(metadata(docs::human_name = "Visibility Timeout"))] pub(super) visibility_timeout_secs: u32, + /// Whether to extend the visibility timeout of messages while they are processed. + /// + /// When enabled, a poller extends the visibility timeout of the messages it holds by + /// `visibility_timeout_secs` each time half of that time has passed. A message then goes back + /// on the queue only if its processing fails or Vector stops. Use this when one message can + /// take longer than `visibility_timeout_secs`, for example a notification that lists many + /// objects. The credentials need the `sqs:ChangeMessageVisibility` permission. SQS limits the + /// total visibility timeout of a message to 12 hours from its receipt. + #[serde(default)] + pub(super) extend_visibility_timeout: bool, + /// Whether to delete the message once it is processed. /// /// It can be useful to set this to `false` for debugging or during the initial setup. @@ -315,6 +332,7 @@ pub struct State { client_concurrency: usize, object_concurrency_per_message: usize, visibility_timeout_secs: i32, + extend_visibility_timeout: bool, delete_message: bool, delete_failed_message: bool, decoder: Decoder, @@ -359,6 +377,7 @@ impl Ingestor { .unwrap_or_else(crate::num_threads), object_concurrency_per_message: config.object_concurrency_per_message.get(), visibility_timeout_secs: config.visibility_timeout_secs as i32, + extend_visibility_timeout: config.extend_visibility_timeout, delete_message: config.delete_message, delete_failed_message: config.delete_failed_message, decoder, @@ -486,6 +505,14 @@ impl IngestorProcess { } }; + let visibility_extender = VisibilityExtender::start( + &self.state, + messages + .iter() + .filter_map(|message| message.receipt_handle.clone()) + .collect(), + ); + let mut delete_entries = Vec::new(); let mut deferred_entries = Vec::new(); for message in messages { @@ -597,6 +624,9 @@ impl IngestorProcess { } } + // Stop before the delete, so that an extension does not race with it. + drop(visibility_extender); + // Should consider removing failed deferrals from the delete_entries if !deferred_entries.is_empty() { let Some(deferred) = &self.state.deferred else { @@ -987,6 +1017,74 @@ impl ObjectReader { } } +/// Extends the visibility timeout of the messages of one receive until it is dropped. +struct VisibilityExtender(tokio::task::JoinHandle<()>); + +impl VisibilityExtender { + fn start(state: &Arc, receipt_handles: Vec) -> Option { + if !state.extend_visibility_timeout + || state.visibility_timeout_secs <= 0 + || receipt_handles.is_empty() + { + return None; + } + let state = Arc::clone(state); + let period = Duration::from_secs((state.visibility_timeout_secs as u64 / 2).max(1)); + let task = async move { + let mut ticks = tokio::time::interval_at(tokio::time::Instant::now() + period, period); + ticks.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + loop { + ticks.tick().await; + extend_visibility(&state, &receipt_handles).await; + } + }; + Some(Self(tokio::spawn(task.in_current_span()))) + } +} + +impl Drop for VisibilityExtender { + fn drop(&mut self) { + self.0.abort(); + } +} + +async fn extend_visibility(state: &State, receipt_handles: &[String]) { + let entries = receipt_handles + .iter() + .enumerate() + .map(|(index, receipt_handle)| { + ChangeMessageVisibilityBatchRequestEntry::builder() + .id(index.to_string()) + .receipt_handle(receipt_handle) + .visibility_timeout(state.visibility_timeout_secs) + .build() + .expect("all required builder params specified") + }) + .collect(); + let result: Result<_, SdkError> = state + .sqs_client + .change_message_visibility_batch() + .queue_url(state.queue_url.clone()) + .set_entries(Some(entries)) + .send() + .await; + match result { + Ok(output) if !output.failed.is_empty() => { + emit!(SqsMessageVisibilityExtendPartialError { + entries: output.failed + }); + } + Ok(_) => trace!( + message = "Extended visibility timeout of SQS messages.", + count = receipt_handles.len(), + ), + Err(error) => emit!(SqsMessageVisibilityExtendBatchError { + count: receipt_handles.len(), + error, + }), + } +} + impl IngestorProcess { async fn receive_messages( &mut self, @@ -1543,6 +1641,18 @@ fn parse_sqs_config_object_concurrency_per_message() { assert!(test.is_err()); } +#[test] +fn parse_sqs_config_extend_visibility_timeout() { + let queue_url = r#"queue_url = "https://sqs.us-east-1.amazonaws.com/123456789012/MyQueue""#; + + let config: Config = toml::from_str(queue_url).unwrap(); + assert!(!config.extend_visibility_timeout); + + let config: Config = + toml::from_str(&format!("{queue_url}\nextend_visibility_timeout = true")).unwrap(); + assert!(config.extend_visibility_timeout); +} + // A real body that no variant matches, kept as a regression case for the parse // failure the delete gate acts on. This one is CloudTrail's own log-file-delivery // notification, which a trail publishes when its SNS topic is shared with the