From 013ddfaf3c72b6d1b1f1cb5088cda3e1ca10064d Mon Sep 17 00:00:00 2001 From: Ferhat Elmas Date: Tue, 10 Nov 2026 14:56:16 +0100 Subject: [PATCH 1/4] feat: add rust job worker with retries and visibility heartbeats Signed-off-by: Ferhat Elmas --- .github/workflows/rust.yml | 4 +- rust/Cargo.lock | 40 + rust/Cargo.toml | 7 +- rust/README.md | 33 +- rust/crates/jobs/Cargo.toml | 21 + rust/crates/jobs/src/lib.rs | 765 ++++++++++ .../jobs/tests/fixtures/node-payload.json | 9 + rust/crates/jobs/tests/sqs.rs | 184 +++ rust/crates/jobs/tests/worker.rs | 1289 +++++++++++++++++ rust/crates/queue/src/lib.rs | 30 +- rust/crates/queue/src/sqs.rs | 63 +- rust/crates/queue/tests/contract.rs | 79 +- rust/crates/queue/tests/failure_paths.rs | 38 +- src/internal/queue/event.test.ts | 23 + 14 files changed, 2485 insertions(+), 100 deletions(-) create mode 100644 rust/crates/jobs/Cargo.toml create mode 100644 rust/crates/jobs/src/lib.rs create mode 100644 rust/crates/jobs/tests/fixtures/node-payload.json create mode 100644 rust/crates/jobs/tests/sqs.rs create mode 100644 rust/crates/jobs/tests/worker.rs diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index e3fa1b84a..89a3d664a 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -50,7 +50,7 @@ jobs: run: timeout 30 sh -c 'until curl -s -o /dev/null http://127.0.0.1:9324; do sleep 1; done' - name: Test run: cargo test --locked - - name: Test SQS contract - run: cargo test --locked --test contract -- --ignored + - name: Test SQS + run: cargo test --locked -- --ignored env: STORAGE_QUEUE_TEST_SQS_ENDPOINT: http://127.0.0.1:9324 diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 7a95615ab..547e7aa97 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -762,6 +762,12 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + [[package]] name = "mio" version = "1.2.4" @@ -1001,6 +1007,19 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + [[package]] name = "sha2" version = "0.11.1" @@ -1040,6 +1059,21 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "storage-jobs" +version = "0.1.0" +dependencies = [ + "aws-sdk-sqs", + "serde", + "serde_json", + "sha2", + "storage-queue", + "thiserror", + "tokio", + "tokio-util", + "tracing", +] + [[package]] name = "storage-queue" version = "0.1.0" @@ -1422,3 +1456,9 @@ name = "zeroize" version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 6541faf58..d5b1c0c7a 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -1,8 +1,13 @@ [workspace] resolver = "3" -members = ["crates/queue"] +members = ["crates/queue", "crates/jobs"] [workspace.dependencies] aws-sdk-sqs = { version = "1.119.0", default-features = false, features = ["behavior-version-latest", "default-https-client", "rt-tokio"] } thiserror = "2.0.21" tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "time"] } +serde = { version = "1.0.229", features = ["derive"] } +serde_json = { version = "1.0.154", features = ["raw_value"] } +tokio-util = "0.7.20" +tracing = { version = "0.1.44", default-features = false, features = ["std"] } +sha2 = "0.11.1" diff --git a/rust/README.md b/rust/README.md index 4ad09cd00..1ef6f0b33 100644 --- a/rust/README.md +++ b/rust/README.md @@ -1,16 +1,33 @@ # Rust workspace -`crates/queue` (`storage-queue`) provides transport primitives with SQS standard-queue semantics -(at-least-once delivery, visibility timeout, receive count, delay, redrive). It currently implements -the transport for AWS SQS. It does not provide event dispatch or job policies. +`crates/queue` provides queue transport primitives, currently backed by SQS standard queues. +`crates/jobs` provides JSON job dispatch, bounded concurrency, visibility heartbeats, retries, +and graceful shutdown. -The SQS contract tests are ignored by default and require an endpoint. From `rust/`: +Jobs use the Node queue manager's bare JSON payload and message attributes. Each worker handles +one job type on one queue. Tenant keys are used as SQS message groups for fair queues; this does +not guarantee ordering or deduplication. All consumers of a queue must support its payloads. - STORAGE_QUEUE_TEST_SQS_ENDPOINT=http://127.0.0.1:9324 \ - cargo test --test contract -- --ignored +Configure visibility, execution timeout, retry policy, and dead-letter settings consistently across +workers sharing a queue. Set retry backoff and attempt limits with `WorkerConfig::retry`. An attempt +limit requires a distinct dead-letter queue supplied through `set_dead_letter`. Provision queues +separately and align their redrive settings. A failed dead-letter copy leaves the original message +for redelivery; a crash after copying can produce duplicates. + +Set `WorkerConfig::execution_timeout` to limit handler runtime. On timeout the worker signals +cancellation, then aborts a handler that exceeds `shutdown_grace` and retries it. Automatic +heartbeats are disabled by default; enable `auto_heartbeat` with an execution timeout to renew +visibility during longer jobs. Without heartbeats, visibility expiry cancels the job. -ElasticMQ (the SQS endpoint) is the `elasticmq` service in `.docker/docker-compose-infra.yml`. +Delivery is at least once, and visibility is advisory. Jobs need their own correctness fences, +such as Postgres claims. Retry delays are capped at 11 hours and by the remaining SQS visibility +window, so a message can reappear earlier than requested. -Start it from the repo root: +The SQS tests require an endpoint and are ignored by default. Start ElasticMQ from the repo root: docker compose --project-directory . -f ./.docker/docker-compose-infra.yml up -d elasticmq + +Then run from `rust/`: + + STORAGE_QUEUE_TEST_SQS_ENDPOINT=http://127.0.0.1:9324 \ + cargo test -- --ignored diff --git a/rust/crates/jobs/Cargo.toml b/rust/crates/jobs/Cargo.toml new file mode 100644 index 000000000..b0c3c8bcb --- /dev/null +++ b/rust/crates/jobs/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "storage-jobs" +version = "0.1.0" +edition = "2024" + +[lib] +name = "storage_jobs" + +[dependencies] +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +storage-queue = { path = "../queue" } +thiserror.workspace = true +tokio = { workspace = true, features = ["sync"] } +tokio-util.workspace = true +tracing.workspace = true + +[dev-dependencies] +aws-sdk-sqs.workspace = true +tokio = { workspace = true, features = ["test-util"] } diff --git a/rust/crates/jobs/src/lib.rs b/rust/crates/jobs/src/lib.rs new file mode 100644 index 000000000..1c987485b --- /dev/null +++ b/rust/crates/jobs/src/lib.rs @@ -0,0 +1,765 @@ +use std::{collections::HashMap, future::Future, pin::Pin, sync::Arc, time::Duration}; + +use serde::{Serialize, de::DeserializeOwned}; +use serde_json::value::RawValue; +use sha2::{Digest, Sha256}; +use storage_queue::{AttributeValue, MessageAttribute, Outgoing, Received, Transport}; +use tokio::{ + sync::Semaphore, + task::{JoinHandle, JoinSet}, + time::{self, Instant}, +}; +use tokio_util::sync::CancellationToken; +use tracing::{Instrument, error, info_span, warn}; + +pub type BoxError = Box; +type BoxFuture = Pin + Send>>; +type Heartbeat<'a> = ( + Instant, + Duration, + Pin> + Send + 'a>>, +); + +const SYSTEM_TENANT_REF: &str = "SYSTEM_TENANT"; +const HEADERS_ATTRIBUTE: &str = "queue.headers"; +const KEY_ATTRIBUTE: &str = "queue.key"; +const MAX_BATCH: usize = 10; +const MAX_WAIT: Duration = Duration::from_secs(20); +const MAX_VISIBILITY: Duration = Duration::from_secs(12 * 60 * 60); +// Matches the Node SQS adapter's cap on parked retries. +const MAX_RETRY_DELAY: Duration = Duration::from_secs(11 * 60 * 60); +// Leave time for the visibility request to reach SQS before its 12-hour deadline. +const VISIBILITY_MARGIN: Duration = Duration::from_secs(5); +const RECEIVE_RETRY_DELAY: Duration = Duration::from_secs(1); +const HEARTBEAT_RETRY: Duration = Duration::from_secs(1); + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("invalid config: {0}")] + InvalidConfig(&'static str), + #[error("encode failed: {0}")] + Encode(#[from] serde_json::Error), +} + +pub trait Job: Send + Sync + 'static { + /// Queue name used by the Node manager's registry. + const NAME: &'static str; + /// Optional manager message type, carried in `queue.headers`. + const TYPE: Option<&'static str> = None; + type Payload: Serialize + DeserializeOwned + Send + 'static; + fn run( + &self, + ctx: Context, + payload: Self::Payload, + ) -> impl Future> + Send; +} + +pub struct Context { + pub tenant: Option, + pub receive_count: u32, + pub key: Option, + pub headers: HashMap, + /// Fires on timeout, shutdown, or when the message lease is lost. + pub cancel: CancellationToken, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Disposition { + Done, + /// Retry using the current receipt's visibility timeout. SQS cannot guarantee + /// delays beyond the remaining 12-hour receive window. + RetryAfter(Duration), +} + +fn payload_tenant(payload: &RawValue) -> Option { + let value = serde_json::from_str::(payload.get()).ok()?; + value.get("tenant")?.get("ref")?.as_str().map(str::to_owned) +} + +fn string_attribute(value: String) -> MessageAttribute { + MessageAttribute { + data_type: "String".into(), + value: AttributeValue::Text(value), + } +} + +fn group_id(key: &str) -> String { + if !key.is_empty() && key.len() <= 128 && key.bytes().all(|b| (0x21..=0x7e).contains(&b)) { + key.to_owned() + } else { + use std::fmt::Write; + let mut result = String::from("sha256:"); + for byte in Sha256::digest(key.as_bytes()) { + write!(&mut result, "{byte:02x}").expect("writing to a string cannot fail"); + } + result + } +} + +#[derive(Debug, Default)] +pub struct EncodeOptions<'a> { + /// Override the key derived from the payload's tenant reference. + pub key: Option<&'a str>, + /// Used as a fair-queue group when there is no key. Standard SQS does not deduplicate it. + pub idempotency_key: Option<&'a str>, + pub headers: HashMap, +} + +/// Encode the bare JSON body and manager attributes for this job's queue. +pub fn encode(payload: &J::Payload) -> Result { + encode_with_options::(payload, EncodeOptions::default()) +} + +pub fn encode_with_options( + payload: &J::Payload, + options: EncodeOptions<'_>, +) -> Result { + let payload = serde_json::value::to_raw_value(payload)?; + let tenant = payload_tenant(&payload).filter(|t| t != SYSTEM_TENANT_REF); + let key = options + .key + .or(tenant.as_deref()) + .filter(|key| !key.is_empty()); + let fair_group = key.or(options.idempotency_key.filter(|key| !key.is_empty())); + let mut attributes = HashMap::new(); + if let Some(key) = key { + attributes.insert(KEY_ATTRIBUTE.into(), string_attribute(key.to_owned())); + } + let mut headers = options.headers; + if let Some(kind) = J::TYPE { + headers + .entry("message-type".into()) + .or_insert_with(|| kind.to_owned()); + } + if !headers.is_empty() { + attributes.insert( + HEADERS_ATTRIBUTE.into(), + string_attribute(serde_json::to_string(&headers)?), + ); + } + Ok(Outgoing { + body: payload.get().to_owned(), + group_id: fair_group.map(group_id), + attributes, + }) +} + +#[derive(Debug, Clone)] +pub struct WorkerConfig { + pub concurrency: usize, + pub batch: usize, + pub wait: Duration, + pub visibility: Duration, + /// Renew visibility while a job runs. Requires an execution timeout. + pub auto_heartbeat: bool, + /// Optional maximum handler runtime before cancellation. + pub execution_timeout: Option, + /// Failure retry policy for this queue. A limit requires a dead-letter transport. + pub retry: RetryPolicy, + /// How long a cancelled job may run before it is aborted. + pub shutdown_grace: Duration, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Backoff { + Fixed, + Exponential, +} + +#[derive(Debug, Clone)] +pub struct RetryPolicy { + /// Maximum deliveries, including crash redeliveries. `None` means no local limit. + pub max_attempts: Option, + pub backoff: Backoff, + pub base: Duration, + pub max: Option, +} + +impl Default for RetryPolicy { + fn default() -> Self { + Self { + max_attempts: None, + backoff: Backoff::Exponential, + base: Duration::from_secs(5), + max: Some(Duration::from_secs(300)), + } + } +} + +impl RetryPolicy { + fn delay(&self, receive_count: u32) -> Duration { + let delay = match self.backoff { + Backoff::Fixed => self.base, + Backoff::Exponential => { + let mut delay = self.base; + if !delay.is_zero() { + for _ in 0..receive_count.saturating_sub(1) { + delay = delay.saturating_mul(2); + // The SQS settle path cannot park longer than this. + if delay >= MAX_RETRY_DELAY { + break; + } + } + } + delay + } + }; + self.max.map_or(delay, |max| delay.min(max)) + } +} + +impl Default for WorkerConfig { + fn default() -> Self { + Self { + concurrency: 16, + batch: MAX_BATCH, + wait: MAX_WAIT, + visibility: Duration::from_secs(60), + auto_heartbeat: false, + execution_timeout: None, + retry: RetryPolicy::default(), + shutdown_grace: Duration::from_secs(30), + } + } +} + +impl WorkerConfig { + fn validate(&self) -> Result<(), Error> { + if !(1..=Semaphore::MAX_PERMITS).contains(&self.concurrency) { + return Err(Error::InvalidConfig( + "concurrency must be 1..=Semaphore::MAX_PERMITS", + )); + } + if !(1..=MAX_BATCH).contains(&self.batch) { + return Err(Error::InvalidConfig("batch must be 1..=10")); + } + if self.wait.subsec_nanos() != 0 || self.wait.is_zero() || self.wait > MAX_WAIT { + return Err(Error::InvalidConfig( + "wait must be whole seconds in 1..=20 s", + )); + } + if self.visibility.subsec_nanos() != 0 + || self.visibility < Duration::from_secs(2) + || self.visibility > MAX_VISIBILITY + { + return Err(Error::InvalidConfig( + "visibility must be whole seconds in 2 s..=12 h", + )); + } + if self.execution_timeout.is_some_and(|timeout| { + timeout.is_zero() || Instant::now().checked_add(timeout).is_none() + }) { + return Err(Error::InvalidConfig( + "execution_timeout must be greater than zero and representable", + )); + } + if self.auto_heartbeat && self.execution_timeout.is_none() { + return Err(Error::InvalidConfig( + "auto_heartbeat requires execution_timeout", + )); + } + if Instant::now().checked_add(self.shutdown_grace).is_none() { + return Err(Error::InvalidConfig("shutdown_grace must be representable")); + } + if self.retry.max_attempts == Some(0) { + return Err(Error::InvalidConfig("max_attempts must be at least 1")); + } + if self.retry.max.is_some_and(|max| max < self.retry.base) { + return Err(Error::InvalidConfig( + "maximum backoff must be at least the base", + )); + } + Ok(()) + } +} + +trait Handler: Send + Sync { + fn start( + &self, + ctx: Context, + payload: &RawValue, + ) -> Result>, serde_json::Error>; +} + +struct Typed(Arc); + +impl Handler for Typed { + fn start( + &self, + ctx: Context, + payload: &RawValue, + ) -> Result>, serde_json::Error> { + let payload = serde_json::from_str(payload.get())?; + let job = self.0.clone(); + Ok(Box::pin(async move { job.run(ctx, payload).await })) + } +} + +struct AbortOnDrop(JoinHandle); + +impl Drop for AbortOnDrop { + fn drop(&mut self) { + self.0.abort(); + } +} + +struct Shared { + transport: Arc, + config: WorkerConfig, + handler: Box, + queue: &'static str, + dead_letter: Option>, + jobs: CancellationToken, +} + +pub struct Worker { + transport: Arc, + config: WorkerConfig, + handler: Option<(&'static str, Box)>, + dead_letter: Option>, +} + +impl Worker { + pub fn new(transport: Arc, config: WorkerConfig) -> Result { + config.validate()?; + Ok(Self { + transport, + config, + handler: None, + dead_letter: None, + }) + } + + /// Bind the single job handled by this queue. Panics if already bound. + pub fn register(&mut self, job: J) { + assert!(self.handler.is_none(), "a job is already registered"); + self.handler = Some((J::NAME, Box::new(Typed(Arc::new(job))))); + } + + /// Supply a distinct queue for exhausted messages. Delivery to it is at least once. + pub fn set_dead_letter(&mut self, transport: Arc) { + self.dead_letter = Some(transport); + } + + pub async fn run(self, shutdown: CancellationToken) -> Result<(), Error> { + let (queue, handler) = self + .handler + .ok_or(Error::InvalidConfig("no job registered"))?; + if self.config.retry.max_attempts.is_some() && self.dead_letter.is_none() { + return Err(Error::InvalidConfig( + "max_attempts requires a dead-letter queue", + )); + } + if self + .dead_letter + .as_ref() + .is_some_and(|dlq| Arc::ptr_eq(dlq, &self.transport)) + { + return Err(Error::InvalidConfig( + "dead-letter queue must be distinct from the source", + )); + } + let grace = self.config.shutdown_grace; + let shared = Arc::new(Shared { + transport: self.transport, + config: self.config, + handler, + queue, + dead_letter: self.dead_letter, + jobs: CancellationToken::new(), + }); + let permits = Arc::new(Semaphore::new(shared.config.concurrency)); + let mut tasks = JoinSet::new(); + + while let Some(messages) = receive(&shared, &permits, &shutdown).await { + for (message, permit, received_at, receive_started) in messages { + let shared = shared.clone(); + tasks.spawn(async move { + handle(&shared, message, received_at, receive_started).await; + drop(permit); + }); + } + while tasks.try_join_next().is_some() {} + } + + shared.jobs.cancel(); + let drain = async { while tasks.join_next().await.is_some() {} }; + if time::timeout(grace, drain).await.is_err() { + warn!("shutdown grace elapsed, aborting in-flight jobs"); + } + tasks.shutdown().await; + Ok(()) + } +} + +async fn receive( + shared: &Shared, + permits: &Arc, + shutdown: &CancellationToken, +) -> Option< + Vec<( + Received, + tokio::sync::OwnedSemaphorePermit, + Instant, + Instant, + )>, +> { + let config = &shared.config; + let first = tokio::select! { + biased; + _ = shutdown.cancelled() => return None, + permit = permits.clone().acquire_owned() => permit.expect("semaphore is never closed"), + }; + let mut held = vec![first]; + while held.len() < config.batch { + match permits.clone().try_acquire_owned() { + Ok(permit) => held.push(permit), + Err(_) => break, + } + } + let receive_started = Instant::now(); + let result = tokio::select! { + biased; + _ = shutdown.cancelled() => return None, + result = shared.transport.receive(held.len(), config.wait, config.visibility) => result, + }; + match result { + Ok(messages) => { + let received_at = Instant::now(); + Some( + messages + .into_iter() + .zip(held) + .map(|(message, permit)| (message, permit, received_at, receive_started)) + .collect(), + ) + } + Err(e) => { + warn!(error = ?e, "receive failed"); + tokio::select! { + _ = shutdown.cancelled() => None, + _ = time::sleep(RECEIVE_RETRY_DELAY) => Some(Vec::new()), + } + } + } +} + +async fn handle( + shared: &Shared, + message: Received, + received_at: Instant, + receive_started: Instant, +) { + let deadline = received_at + shared.config.visibility; + if shared + .config + .retry + .max_attempts + .is_some_and(|max| message.receive_count > max) + { + if let Err(e) = dead_letter(shared, &message, deadline).await { + warn!(error = ?e, "dead-lettering failed; original message remains in the queue"); + } + return; + } + let payload = match serde_json::from_str::>(&message.body) { + Ok(payload) => payload, + Err(e) => { + warn!(error = %e, receive_count = message.receive_count, "invalid JSON payload"); + if let Err(e) = retry_later(shared, &message, receive_started, deadline).await { + warn!(error = ?e, "disposition failed"); + } + return; + } + }; + let tenant = payload_tenant(&payload); + let span = info_span!( + "job", + name = %shared.queue, + tenant = ?tenant, + receive_count = message.receive_count + ); + process( + shared, + message, + payload, + tenant, + received_at, + receive_started, + ) + .instrument(span) + .await; +} + +fn text_attribute<'a>(message: &'a Received, name: &str) -> Option<&'a str> { + match &message.attributes.get(name)?.value { + AttributeValue::Text(text) => Some(text), + AttributeValue::Binary(_) => None, + } +} + +fn message_headers(message: &Received) -> HashMap { + if let Some(packed) = text_attribute(message, HEADERS_ATTRIBUTE) { + return match serde_json::from_str::(packed) { + Ok(serde_json::Value::Object(headers)) => headers + .into_iter() + .filter_map(|(name, value)| value.as_str().map(|text| (name, text.to_owned()))) + .collect(), + _ => HashMap::new(), + }; + } + message + .attributes + .iter() + .filter_map(|(name, attribute)| { + if name.starts_with("queue.") || attribute.data_type.starts_with("Binary") { + return None; + } + match &attribute.value { + AttributeValue::Text(value) => Some((name.clone(), value.clone())), + AttributeValue::Binary(_) => None, + } + }) + .collect() +} + +async fn process( + shared: &Shared, + message: Received, + payload: Box, + tenant: Option, + received_at: Instant, + receive_started: Instant, +) { + let cancel = shared.jobs.child_token(); + let ctx = Context { + tenant, + receive_count: message.receive_count, + key: text_attribute(&message, KEY_ATTRIBUTE).map(str::to_owned), + headers: message_headers(&message), + cancel: cancel.clone(), + }; + let future = match shared.handler.start(ctx, &payload) { + Ok(future) => future, + Err(e) => { + warn!(error = %e, "invalid payload"); + if let Err(e) = retry_later( + shared, + &message, + receive_started, + received_at + shared.config.visibility, + ) + .await + { + warn!(error = ?e, "disposition failed"); + } + return; + } + }; + let execution_deadline = shared + .config + .execution_timeout + .map(|timeout| Instant::now() + timeout); + let mut job = AbortOnDrop(tokio::spawn(future.in_current_span())); + + let visibility = shared.config.visibility; + let half = visibility / 2; + let mut next_beat = received_at + half; + let mut heartbeat: Option> = None; + let mut lease_deadline = received_at + visibility; + let mut cancel_deadline = None; + let mut timed_out = false; + // Lease-loss branches precede the job so that a ready loss is never ignored. + let joined = loop { + tokio::select! { + biased; + _ = time::sleep_until(lease_deadline) => { + warn!("visibility expired, cancelling job"); + break None; + } + result = async { heartbeat.as_mut().expect("guarded").2.as_mut().await }, if heartbeat.is_some() => { + let (started, duration, _) = heartbeat.take().expect("guarded"); + match result { + Ok(()) => { + lease_deadline = started + duration; + next_beat = started + half; + } + Err(storage_queue::Error::StaleReceipt) => { + warn!("lease lost, cancelling job"); + break None; + } + Err(e) => { + warn!(error = ?e, "heartbeat failed"); + next_beat = Instant::now() + HEARTBEAT_RETRY.min(half); + } + } + } + joined = &mut job.0 => break Some(joined), + _ = async { time::sleep_until(execution_deadline.expect("guarded")).await }, if execution_deadline.is_some() && cancel_deadline.is_none() => { + warn!("job execution timed out, cancelling job"); + cancel.cancel(); + cancel_deadline = Some(Instant::now() + shared.config.shutdown_grace); + } + _ = async { time::sleep_until(cancel_deadline.expect("guarded")).await }, if cancel_deadline.is_some() => { + warn!("job ignored cancellation, aborting"); + job.0.abort(); + let joined = (&mut job.0).await; + timed_out = matches!(&joined, Err(e) if e.is_cancelled()); + break Some(joined); + } + _ = time::sleep_until(next_beat), if shared.config.auto_heartbeat && heartbeat.is_none() => { + let started = Instant::now(); + let duration = visibility.min(remaining_window(receive_started, started)); + if duration.is_zero() { + warn!("visibility window exhausted, cancelling job"); + break None; + } + heartbeat = Some(( + started, + duration, + Box::pin(shared.transport.extend(&message.receipt, duration)), + )); + } + } + }; + let Some(joined) = joined else { + // A lost lease must not settle a delivery that may now be owned elsewhere. + cancel.cancel(); + if time::timeout(shared.config.shutdown_grace, &mut job.0) + .await + .is_err() + { + warn!("job ignored cancellation, aborting"); + } + return; + }; + + if !matches!(joined, Ok(Ok(Disposition::Done))) { + // A late heartbeat would override the retry delay. + if let Some((started, duration, extend)) = heartbeat { + match time::timeout_at(lease_deadline, extend).await { + Ok(Ok(())) => lease_deadline = started + duration, + Ok(Err(storage_queue::Error::StaleReceipt)) => return, + Ok(Err(_)) | Err(_) => {} + } + } + } + if Instant::now() >= lease_deadline { + return; + } + let result = if timed_out { + if shared.jobs.is_cancelled() { + extend(shared, &message, Duration::ZERO, receive_started).await + } else { + retry_later(shared, &message, receive_started, lease_deadline).await + } + } else { + match joined { + Ok(Ok(Disposition::Done)) => shared.transport.delete(&[&message.receipt]).await, + Ok(Ok(Disposition::RetryAfter(delay))) => { + if shared.jobs.is_cancelled() { + extend(shared, &message, Duration::ZERO, receive_started).await + } else if exhausted(shared, &message) { + dead_letter(shared, &message, lease_deadline).await + } else { + extend(shared, &message, delay, receive_started).await + } + } + Ok(Err(e)) => { + error!(error = %e, "job failed"); + if shared.jobs.is_cancelled() { + extend(shared, &message, Duration::ZERO, receive_started).await + } else { + retry_later(shared, &message, receive_started, lease_deadline).await + } + } + Err(e) => { + error!(error = %e, "job panicked"); + retry_later(shared, &message, receive_started, lease_deadline).await + } + } + }; + if let Err(e) = result { + warn!(error = ?e, "disposition failed, message will reappear after visibility timeout"); + } +} + +async fn retry_later( + shared: &Shared, + message: &Received, + receive_started: Instant, + lease_deadline: Instant, +) -> Result<(), storage_queue::Error> { + if exhausted(shared, message) { + dead_letter(shared, message, lease_deadline).await + } else { + extend( + shared, + message, + shared.config.retry.delay(message.receive_count), + receive_started, + ) + .await + } +} + +fn exhausted(shared: &Shared, message: &Received) -> bool { + shared + .config + .retry + .max_attempts + .is_some_and(|max| message.receive_count >= max) +} + +async fn dead_letter( + shared: &Shared, + message: &Received, + lease_deadline: Instant, +) -> Result<(), storage_queue::Error> { + let Some(destination) = &shared.dead_letter else { + return Err(storage_queue::Error::InvalidArgument( + "dead-letter queue is not configured", + )); + }; + let copy = Outgoing { + body: message.body.clone(), + group_id: message.group_id.clone(), + attributes: message.attributes.clone(), + }; + time::timeout_at(lease_deadline, destination.send(&[copy])) + .await + .map_err(|_| storage_queue::Error::StaleReceipt)??; + if Instant::now() >= lease_deadline { + return Err(storage_queue::Error::StaleReceipt); + } + shared.transport.delete(&[&message.receipt]).await +} + +async fn extend( + shared: &Shared, + message: &Received, + delay: Duration, + receive_started: Instant, +) -> Result<(), storage_queue::Error> { + let secs = delay + .as_secs() + .saturating_add(u64::from(delay.subsec_nanos() > 0)); + let remaining = remaining_window(receive_started, Instant::now()).min(MAX_RETRY_DELAY); + let delay = if secs > remaining.as_secs() { + warn!( + requested_seconds = secs, + remaining_seconds = remaining.as_secs(), + "retry delay shortened to the supported visibility window" + ); + remaining + } else { + Duration::from_secs(secs) + }; + shared.transport.extend(&message.receipt, delay).await +} + +fn remaining_window(receive_started: Instant, now: Instant) -> Duration { + let remaining = + (receive_started + MAX_VISIBILITY - VISIBILITY_MARGIN).saturating_duration_since(now); + Duration::from_secs(remaining.as_secs()) +} diff --git a/rust/crates/jobs/tests/fixtures/node-payload.json b/rust/crates/jobs/tests/fixtures/node-payload.json new file mode 100644 index 000000000..cbe8e7ae7 --- /dev/null +++ b/rust/crates/jobs/tests/fixtures/node-payload.json @@ -0,0 +1,9 @@ +{ + "$version": "v-test", + "name": "test-object", + "tenant": { + "ref": "test-tenant", + "host": "localhost" + }, + "reqId": "req-123" +} diff --git a/rust/crates/jobs/tests/sqs.rs b/rust/crates/jobs/tests/sqs.rs new file mode 100644 index 000000000..e7429b457 --- /dev/null +++ b/rust/crates/jobs/tests/sqs.rs @@ -0,0 +1,184 @@ +use std::{ + sync::{ + Arc, Mutex, + atomic::{AtomicUsize, Ordering}, + }, + time::Duration, +}; + +use aws_sdk_sqs::{ + Client, + config::{BehaviorVersion, Credentials, Region}, +}; +use serde::{Deserialize, Serialize}; +use storage_jobs::{ + BoxError, Context, Disposition, Job, RetryPolicy, Worker, WorkerConfig, encode, +}; +use storage_queue::{Transport, sqs::SqsQueue}; +use tokio::time::{Instant, sleep}; +use tokio_util::sync::CancellationToken; + +const SQS_ENDPOINT: &str = "STORAGE_QUEUE_TEST_SQS_ENDPOINT"; +static NEXT_QUEUE: AtomicUsize = AtomicUsize::new(0); + +#[derive(Serialize, Deserialize)] +struct Payload { + tenant: Tenant, + id: u32, + retry_once: bool, +} + +#[derive(Serialize, Deserialize)] +struct Tenant { + #[serde(rename = "ref")] + reference: String, + host: String, +} + +struct Echo(Arc>>); + +impl Job for Echo { + const NAME: &'static str = "echo"; + type Payload = Payload; + + async fn run(&self, ctx: Context, payload: Payload) -> Result { + if payload.retry_once && ctx.receive_count == 1 { + return Ok(Disposition::RetryAfter(Duration::from_secs(1))); + } + self.0.lock().unwrap().push((payload.id, ctx.receive_count)); + Ok(Disposition::Done) + } +} + +async fn queue() -> SqsQueue { + let endpoint = + std::env::var(SQS_ENDPOINT).expect("STORAGE_QUEUE_TEST_SQS_ENDPOINT must be set"); + let config = aws_sdk_sqs::Config::builder() + .behavior_version(BehaviorVersion::latest()) + .endpoint_url(endpoint) + .region(Region::new("us-east-1")) + .credentials_provider(Credentials::new("x", "x", None, None, "test")) + .build(); + let client = Client::from_conf(config); + let name = format!( + "jobs-worker-{}-{}", + std::process::id(), + NEXT_QUEUE.fetch_add(1, Ordering::Relaxed) + ); + let url = client + .create_queue() + .queue_name(name) + .send() + .await + .unwrap() + .queue_url + .unwrap(); + SqsQueue::new(client, url) +} + +#[tokio::test] +#[ignore = "requires an SQS-compatible endpoint"] +async fn exhausted_delivery_preserves_payload_and_attributes_in_dlq() { + let source = Arc::new(queue().await); + let dlq = Arc::new(queue().await); + let payload = Payload { + tenant: Tenant { + reference: "tenant-1".into(), + host: "localhost".into(), + }, + id: 10, + retry_once: true, + }; + let original = encode::(&payload).unwrap(); + source.send(std::slice::from_ref(&original)).await.unwrap(); + + let mut worker = Worker::new( + source, + WorkerConfig { + wait: Duration::from_secs(1), + retry: RetryPolicy { + max_attempts: Some(1), + ..RetryPolicy::default() + }, + ..WorkerConfig::default() + }, + ) + .unwrap(); + worker.set_dead_letter(dlq.clone()); + worker.register(Echo(Arc::new(Mutex::new(Vec::new())))); + let shutdown = CancellationToken::new(); + let handle = tokio::spawn(worker.run(shutdown.clone())); + let deadline = Instant::now() + Duration::from_secs(15); + let message = loop { + let received = dlq + .receive(1, Duration::from_secs(1), Duration::from_secs(2)) + .await + .unwrap(); + if let Some(message) = received.into_iter().next() { + break message; + } + assert!( + Instant::now() < deadline, + "message did not reach the dead-letter queue" + ); + }; + assert_eq!(message.body, original.body); + assert_eq!(message.attributes, original.attributes); + assert_eq!(message.group_id, original.group_id); + shutdown.cancel(); + handle.await.unwrap().unwrap(); +} + +#[tokio::test] +#[ignore = "requires an SQS-compatible endpoint"] +async fn processes_jobs_and_drains_queue() { + let queue = Arc::new(queue().await); + let done = Arc::new(Mutex::new(Vec::new())); + + let jobs: Vec<_> = (0..4) + .map(|id| { + let payload = Payload { + tenant: Tenant { + reference: format!("tenant-{id}"), + host: "localhost".into(), + }, + id, + retry_once: id == 3, + }; + encode::(&payload).unwrap() + }) + .collect(); + queue.send(&jobs).await.unwrap(); + + let mut worker = Worker::new( + queue.clone(), + WorkerConfig { + wait: Duration::from_secs(1), + visibility: Duration::from_secs(5), + ..WorkerConfig::default() + }, + ) + .unwrap(); + worker.register(Echo(done.clone())); + let shutdown = CancellationToken::new(); + let handle = tokio::spawn(worker.run(shutdown.clone())); + + let deadline = Instant::now() + Duration::from_secs(20); + while done.lock().unwrap().len() < 4 { + assert!(Instant::now() < deadline, "jobs did not complete"); + sleep(Duration::from_millis(100)).await; + } + shutdown.cancel(); + handle.await.unwrap().unwrap(); + + let mut done = done.lock().unwrap().clone(); + done.sort(); + assert_eq!(done, [(0, 1), (1, 1), (2, 1), (3, 2)]); + assert!( + queue + .receive(10, Duration::ZERO, Duration::from_secs(1)) + .await + .unwrap() + .is_empty() + ); +} diff --git a/rust/crates/jobs/tests/worker.rs b/rust/crates/jobs/tests/worker.rs new file mode 100644 index 000000000..21f9d9006 --- /dev/null +++ b/rust/crates/jobs/tests/worker.rs @@ -0,0 +1,1289 @@ +use std::{ + sync::{ + Arc, Mutex, + atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering::SeqCst}, + }, + time::Duration, +}; + +use serde::{Deserialize, Serialize}; +use storage_jobs::{ + Backoff, BoxError, Context, Disposition, EncodeOptions, Error, Job, RetryPolicy, Worker, + WorkerConfig, encode, encode_with_options, +}; +use storage_queue::{AttributeValue, MessageAttribute, Outgoing, Received, Transport}; +use tokio::{ + sync::{Notify, Semaphore}, + task::JoinHandle, + time::{Instant, sleep}, +}; +use tokio_util::sync::CancellationToken; + +const S1: Duration = Duration::from_secs(1); + +#[derive(Serialize, Deserialize)] +enum Mode { + Done, + Retry(u64), + Fail, + Panic, + Sleep(u64), + SleepRetry(u64, u64), + UntilCancel, + DoneOnCancel, + Ignore, +} + +#[derive(Default)] +struct Stats { + running: AtomicUsize, + max_running: AtomicUsize, + started: AtomicUsize, + cancelled: AtomicUsize, + exited: AtomicUsize, + exit: Notify, +} + +struct Running(Arc); + +impl Drop for Running { + fn drop(&mut self) { + self.0.running.fetch_sub(1, SeqCst); + self.0.exited.fetch_add(1, SeqCst); + self.0.exit.notify_one(); + } +} + +struct Probe(Arc); + +impl Job for Probe { + const NAME: &'static str = "probe"; + type Payload = Mode; + + async fn run(&self, ctx: Context, mode: Mode) -> Result { + self.0.started.fetch_add(1, SeqCst); + let now = self.0.running.fetch_add(1, SeqCst) + 1; + self.0.max_running.fetch_max(now, SeqCst); + let _running = Running(self.0.clone()); + match mode { + Mode::Done => Ok(Disposition::Done), + Mode::Retry(ms) => Ok(Disposition::RetryAfter(Duration::from_millis(ms))), + Mode::Fail => Err("boom".into()), + Mode::Panic => panic!("boom"), + Mode::Sleep(ms) => { + sleep(Duration::from_millis(ms)).await; + Ok(Disposition::Done) + } + Mode::SleepRetry(sleep_ms, retry_ms) => { + sleep(Duration::from_millis(sleep_ms)).await; + Ok(Disposition::RetryAfter(Duration::from_millis(retry_ms))) + } + Mode::UntilCancel => { + ctx.cancel.cancelled().await; + self.0.cancelled.fetch_add(1, SeqCst); + Ok(Disposition::RetryAfter(Duration::ZERO)) + } + Mode::DoneOnCancel => { + ctx.cancel.cancelled().await; + self.0.cancelled.fetch_add(1, SeqCst); + Ok(Disposition::Done) + } + Mode::Ignore => std::future::pending().await, + } + } +} + +type RecordedPayloads = Arc, serde_json::Value)>>>; +struct NodeEvent(RecordedPayloads); + +impl Job for NodeEvent { + const NAME: &'static str = "test-event"; + const TYPE: Option<&'static str> = Some("TestEvent"); + type Payload = serde_json::Value; + + async fn run(&self, ctx: Context, payload: Self::Payload) -> Result { + self.0.lock().unwrap().push((ctx.tenant, payload)); + Ok(Disposition::Done) + } +} + +#[derive(Clone, Debug)] +enum Call { + Send, + Receive { max: usize, running: usize }, + Extend(String, Duration, Instant), + Delete(String), +} + +struct Msg { + receipt: String, + body: String, + count: u32, + visible_at: Instant, + group_id: Option, + attributes: std::collections::HashMap, +} + +struct Fake { + stats: Arc, + msgs: Mutex>, + calls: Mutex>, + stale: Mutex, + fail_receives: AtomicUsize, + fail_sends: AtomicBool, + block_extends: AtomicBool, + fail_extends: AtomicUsize, + extend_delay_ms: AtomicU64, + extend_until_exit: AtomicBool, +} + +impl Fake { + fn new(stats: &Arc) -> Arc { + Arc::new(Self { + stats: stats.clone(), + msgs: Mutex::default(), + calls: Mutex::default(), + stale: Mutex::default(), + fail_receives: AtomicUsize::new(0), + fail_sends: AtomicBool::new(false), + block_extends: AtomicBool::new(false), + fail_extends: AtomicUsize::new(0), + extend_delay_ms: AtomicU64::new(0), + extend_until_exit: AtomicBool::new(false), + }) + } + + fn push(&self, body: String, count: u32) -> String { + let mut msgs = self.msgs.lock().unwrap(); + let receipt = format!("r{}", msgs.len()); + msgs.push(Msg { + receipt: receipt.clone(), + body, + count, + visible_at: Instant::now(), + group_id: None, + attributes: Default::default(), + }); + receipt + } + + fn push_mode(&self, mode: &Mode, count: u32) -> String { + self.push(job_body(mode), count) + } + + fn calls(&self) -> Vec { + self.calls.lock().unwrap().clone() + } + + fn extends(&self) -> Vec<(String, Duration, Instant)> { + self.calls() + .into_iter() + .filter_map(|c| match c { + Call::Extend(r, d, at) => Some((r, d, at)), + _ => None, + }) + .collect() + } + + fn deletes(&self) -> Vec { + self.calls() + .into_iter() + .filter_map(|c| match c { + Call::Delete(r) => Some(r), + _ => None, + }) + .collect() + } + + fn receives(&self) -> usize { + self.calls() + .iter() + .filter(|c| matches!(c, Call::Receive { .. })) + .count() + } + + fn counts(&self) -> Vec { + self.msgs.lock().unwrap().iter().map(|m| m.count).collect() + } +} + +impl Transport for Fake { + async fn send(&self, messages: &[Outgoing]) -> Result<(), storage_queue::Error> { + self.calls.lock().unwrap().push(Call::Send); + if self.fail_sends.load(SeqCst) { + return Err(storage_queue::Error::InvalidResponse( + "injected send failure", + )); + } + for m in messages { + let receipt = self.push(m.body.clone(), 0); + let mut msgs = self.msgs.lock().unwrap(); + let msg = msgs.iter_mut().find(|msg| msg.receipt == receipt).unwrap(); + msg.group_id = m.group_id.clone(); + msg.attributes = m.attributes.clone(); + } + Ok(()) + } + + async fn receive( + &self, + max: usize, + wait: Duration, + visibility: Duration, + ) -> Result, storage_queue::Error> { + self.calls.lock().unwrap().push(Call::Receive { + max, + running: self.stats.running.load(SeqCst), + }); + if self + .fail_receives + .try_update(SeqCst, SeqCst, |n| n.checked_sub(1)) + .is_ok() + { + return Err(storage_queue::Error::InvalidResponse("injected")); + } + let deadline = Instant::now() + wait; + loop { + let now = Instant::now(); + let got: Vec = self + .msgs + .lock() + .unwrap() + .iter_mut() + .filter(|m| m.visible_at <= now) + .take(max) + .map(|m| { + m.count += 1; + m.visible_at = now + visibility; + Received { + receipt: m.receipt.clone(), + body: m.body.clone(), + receive_count: m.count, + group_id: m.group_id.clone(), + attributes: m.attributes.clone(), + } + }) + .collect(); + if !got.is_empty() || now >= deadline { + return Ok(got); + } + sleep(Duration::from_millis(100)).await; + } + } + + async fn extend( + &self, + receipt: &str, + visibility: Duration, + ) -> Result<(), storage_queue::Error> { + assert!( + visibility.subsec_nanos() == 0 && visibility <= Duration::from_secs(12 * 3600), + "invalid visibility {visibility:?}" + ); + let now = Instant::now(); + self.calls + .lock() + .unwrap() + .push(Call::Extend(receipt.into(), visibility, now)); + if self.block_extends.load(SeqCst) { + std::future::pending::<()>().await; + } + if self.extend_until_exit.load(SeqCst) { + self.stats.exit.notified().await; + } + let delay = self.extend_delay_ms.load(SeqCst); + if delay > 0 { + sleep(Duration::from_millis(delay)).await; + } + if self + .fail_extends + .try_update(SeqCst, SeqCst, |n| n.checked_sub(1)) + .is_ok() + { + return Err(storage_queue::Error::InvalidResponse( + "injected heartbeat failure", + )); + } + if *self.stale.lock().unwrap() { + return Err(storage_queue::Error::StaleReceipt); + } + if let Some(m) = self + .msgs + .lock() + .unwrap() + .iter_mut() + .find(|m| m.receipt == receipt) + { + m.visible_at = now + visibility; + } + Ok(()) + } + + async fn delete(&self, receipts: &[&str]) -> Result<(), storage_queue::Error> { + for r in receipts { + self.calls.lock().unwrap().push(Call::Delete((*r).into())); + self.msgs.lock().unwrap().retain(|m| m.receipt != *r); + } + Ok(()) + } +} + +fn job_body(mode: &Mode) -> String { + serde_json::to_string(mode).unwrap() +} + +fn setup(config: WorkerConfig) -> (Arc, Arc, Worker) { + let stats = Arc::new(Stats::default()); + let fake = Fake::new(&stats); + let mut worker = Worker::new(fake.clone(), config).unwrap(); + worker.register(Probe(stats.clone())); + (stats, fake, worker) +} + +fn start(worker: Worker) -> (CancellationToken, JoinHandle>) { + let token = CancellationToken::new(); + (token.clone(), tokio::spawn(worker.run(token))) +} + +async fn stop(token: CancellationToken, handle: JoinHandle>) { + token.cancel(); + handle.await.unwrap().unwrap(); +} + +async fn until(mut done: impl FnMut() -> bool) { + for _ in 0..10_000 { + if done() { + return; + } + sleep(Duration::from_millis(10)).await; + } + panic!("condition not reached"); +} + +#[test] +fn encode_node_payload() { + let expected: serde_json::Value = + serde_json::from_str(include_str!("fixtures/node-payload.json")).unwrap(); + let out = encode::(&expected).unwrap(); + assert_eq!( + serde_json::from_str::(&out.body).unwrap(), + expected + ); + assert_eq!(out.group_id.as_deref(), Some("test-tenant")); + assert_eq!( + out.attributes["queue.key"].value, + AttributeValue::Text("test-tenant".into()) + ); + assert_eq!( + out.attributes["queue.headers"].value, + AttributeValue::Text(r#"{"message-type":"TestEvent"}"#.into()) + ); +} + +#[test] +fn encode_accepts_non_storage_payloads_without_grouping() { + for payload in [ + serde_json::json!({}), + serde_json::json!({"tenant": {"ref": "test-tenant"}}), + serde_json::json!({"tenant": {"ref": 42, "host": "localhost"}}), + ] { + if payload["tenant"]["ref"] == "test-tenant" { + assert_eq!( + encode::(&payload).unwrap().group_id.as_deref(), + Some("test-tenant") + ); + } else { + assert!(encode::(&payload).unwrap().group_id.is_none()); + } + } +} + +#[test] +fn fair_group_matches_manager_for_system_and_non_ascii_keys() { + let system = serde_json::json!({"tenant": {"ref": "SYSTEM_TENANT", "host": ""}}); + let encoded = encode::(&system).unwrap(); + assert!(encoded.group_id.is_none()); + assert!(!encoded.attributes.contains_key("queue.key")); + let fallback = encode_with_options::( + &system, + EncodeOptions { + idempotency_key: Some("dedup-id"), + ..EncodeOptions::default() + }, + ) + .unwrap(); + assert_eq!(fallback.group_id.as_deref(), Some("dedup-id")); + assert!(!fallback.attributes.contains_key("queue.key")); + + let spaced = serde_json::json!({"tenant": {"ref": "tenant with spaces", "host": "localhost"}}); + let encoded = encode::(&spaced).unwrap(); + assert_eq!( + encoded.group_id.as_deref(), + Some("sha256:60d9d80137733115ce9492acf315e5ff47020c01e5e094384ec65c58b7a5bbcc") + ); + assert_eq!( + encoded.attributes["queue.key"].value, + AttributeValue::Text("tenant with spaces".into()) + ); + let override_ = encode_with_options::( + &spaced, + EncodeOptions { + key: Some("custom-key"), + headers: std::collections::HashMap::from([( + "message-type".into(), + "custom-type".into(), + )]), + ..EncodeOptions::default() + }, + ) + .unwrap(); + assert_eq!(override_.group_id.as_deref(), Some("custom-key")); + assert_eq!( + override_.attributes["queue.headers"].value, + AttributeValue::Text(r#"{"message-type":"custom-type"}"#.into()) + ); + let empty_key = encode_with_options::( + &spaced, + EncodeOptions { + key: Some(""), + idempotency_key: Some("dedup-id"), + ..EncodeOptions::default() + }, + ) + .unwrap(); + assert_eq!(empty_key.group_id.as_deref(), Some("dedup-id")); + assert!(!empty_key.attributes.contains_key("queue.key")); +} + +type RecordedMetadata = + Arc, std::collections::HashMap)>>>; +struct MetadataProbe(RecordedMetadata); + +impl Job for MetadataProbe { + const NAME: &'static str = "metadata"; + type Payload = serde_json::Value; + + async fn run(&self, ctx: Context, _payload: Self::Payload) -> Result { + *self.0.lock().unwrap() = Some((ctx.key, ctx.headers)); + Ok(Disposition::Done) + } +} + +#[tokio::test(start_paused = true)] +async fn worker_reads_manager_key_and_headers() { + let stats = Arc::new(Stats::default()); + let fake = Fake::new(&stats); + let output = Arc::new(Mutex::new(None)); + let mut worker = Worker::new(fake.clone(), WorkerConfig::default()).unwrap(); + worker.register(MetadataProbe(output.clone())); + let message = Outgoing { + body: "{}".into(), + group_id: Some("tenant-a".into()), + attributes: std::collections::HashMap::from([ + ( + "queue.key".into(), + MessageAttribute { + data_type: "String".into(), + value: AttributeValue::Text("tenant-a".into()), + }, + ), + ( + "queue.headers".into(), + MessageAttribute { + data_type: "String".into(), + value: AttributeValue::Text( + r#"{"message-type":"Thing","extra":"value","ignored":42}"#.into(), + ), + }, + ), + ]), + }; + fake.send(&[message]).await.unwrap(); + let (token, handle) = start(worker); + until(|| output.lock().unwrap().is_some()).await; + let result = output.lock().unwrap().clone().unwrap(); + assert_eq!(result.0.as_deref(), Some("tenant-a")); + assert_eq!( + result.1, + std::collections::HashMap::from([ + ("message-type".into(), "Thing".into()), + ("extra".into(), "value".into()) + ]) + ); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn worker_accepts_node_payload_and_derives_context_from_it() { + let stats = Arc::new(Stats::default()); + let fake = Fake::new(&stats); + let handled = Arc::new(Mutex::new(Vec::new())); + let mut worker = Worker::new(fake.clone(), WorkerConfig::default()).unwrap(); + worker.register(NodeEvent(handled.clone())); + let body = include_str!("fixtures/node-payload.json"); + let expected: serde_json::Value = serde_json::from_str(body).unwrap(); + let receipt = fake.push(body.into(), 0); + let (token, handle) = start(worker); + until(|| !fake.deletes().is_empty()).await; + assert_eq!(fake.deletes(), [receipt]); + assert_eq!( + *handled.lock().unwrap(), + [(Some("test-tenant".into()), expected)] + ); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn manager_payload_resembling_an_envelope_is_not_unwrapped() { + let stats = Arc::new(Stats::default()); + let fake = Fake::new(&stats); + let handled = Arc::new(Mutex::new(Vec::new())); + let mut worker = Worker::new(fake.clone(), WorkerConfig::default()).unwrap(); + worker.register(NodeEvent(handled.clone())); + let payload = serde_json::json!({"v":2,"name":"test-event","payload":{"value":1}}); + fake.push(payload.to_string(), 0); + let (token, handle) = start(worker); + until(|| !fake.deletes().is_empty()).await; + assert_eq!(*handled.lock().unwrap(), [(None, payload)]); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn done_deletes() { + let (_, fake, worker) = setup(WorkerConfig::default()); + let r = fake.push_mode(&Mode::Done, 0); + let (token, handle) = start(worker); + until(|| !fake.deletes().is_empty()).await; + sleep(S1).await; + assert_eq!(fake.deletes(), [r]); + assert!(fake.extends().is_empty()); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn retry_after_rounds_up() { + let (_, fake, worker) = setup(WorkerConfig::default()); + let r = fake.push_mode(&Mode::Retry(1200), 0); + let (token, handle) = start(worker); + until(|| !fake.extends().is_empty()).await; + sleep(S1).await; + let extends = fake.extends(); + assert_eq!(extends.len(), 1); + assert_eq!( + (extends[0].0.as_str(), extends[0].1), + (r.as_str(), Duration::from_secs(2)) + ); + assert!(fake.deletes().is_empty()); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn error_backs_off_exponentially_with_cap() { + let (_, fake, worker) = setup(WorkerConfig::default()); + let first = fake.push_mode(&Mode::Fail, 0); + let third = fake.push_mode(&Mode::Fail, 2); + let capped = fake.push_mode(&Mode::Fail, 9); + let (token, handle) = start(worker); + until(|| fake.extends().len() == 3).await; + let by_receipt = |r: &str| fake.extends().into_iter().find(|e| e.0 == r).unwrap().1; + assert_eq!(by_receipt(&first), Duration::from_secs(5)); + assert_eq!(by_receipt(&third), Duration::from_secs(20)); + assert_eq!(by_receipt(&capped), Duration::from_secs(300)); + assert!(fake.deletes().is_empty()); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn fixed_backoff_is_per_queue() { + let (_, fake, worker) = setup(WorkerConfig { + retry: RetryPolicy { + backoff: Backoff::Fixed, + base: Duration::from_secs(7), + max: None, + max_attempts: None, + }, + ..WorkerConfig::default() + }); + let first = fake.push_mode(&Mode::Fail, 0); + let later = fake.push_mode(&Mode::Fail, 3); + let (token, handle) = start(worker); + until(|| fake.extends().len() == 2).await; + for receipt in [first, later] { + let delay = fake + .extends() + .into_iter() + .find(|e| e.0 == receipt) + .unwrap() + .1; + assert_eq!(delay, Duration::from_secs(7)); + } + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn exponential_backoff_keeps_growing_past_u32_factor() { + let (_, fake, worker) = setup(WorkerConfig { + retry: RetryPolicy { + backoff: Backoff::Exponential, + base: Duration::from_nanos(1), + max: None, + max_attempts: None, + }, + ..WorkerConfig::default() + }); + fake.push_mode(&Mode::Fail, 39); + let (token, handle) = start(worker); + until(|| !fake.extends().is_empty()).await; + assert_eq!(fake.extends()[0].1, Duration::from_secs(550)); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn exhausted_delivery_is_copied_before_ack_with_metadata() { + let (stats, fake, mut worker) = setup(WorkerConfig { + retry: RetryPolicy { + max_attempts: Some(2), + ..RetryPolicy::default() + }, + ..WorkerConfig::default() + }); + let dlq = Fake::new(&stats); + worker.set_dead_letter(dlq.clone()); + let receipt = fake.push_mode(&Mode::Fail, 1); + { + let mut msgs = fake.msgs.lock().unwrap(); + let message = &mut msgs[0]; + message.group_id = Some("tenant-a".into()); + message.attributes.insert( + "queue.key".into(), + MessageAttribute { + data_type: "String".into(), + value: AttributeValue::Text("tenant-a".into()), + }, + ); + } + let (token, handle) = start(worker); + until(|| !fake.deletes().is_empty()).await; + assert_eq!(fake.deletes(), [receipt]); + { + let copied = dlq.msgs.lock().unwrap(); + assert_eq!(copied.len(), 1); + assert_eq!(copied[0].body, job_body(&Mode::Fail)); + assert_eq!(copied[0].group_id.as_deref(), Some("tenant-a")); + assert_eq!( + copied[0].attributes["queue.key"].value, + AttributeValue::Text("tenant-a".into()) + ); + } + assert!(fake.extends().is_empty()); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn failed_dead_letter_send_keeps_original_for_retry() { + let (stats, fake, mut worker) = setup(WorkerConfig { + visibility: Duration::from_secs(2), + retry: RetryPolicy { + max_attempts: Some(1), + ..RetryPolicy::default() + }, + ..WorkerConfig::default() + }); + let dlq = Fake::new(&stats); + dlq.fail_sends.store(true, SeqCst); + worker.set_dead_letter(dlq.clone()); + fake.push_mode(&Mode::Fail, 0); + let (token, handle) = start(worker); + until(|| dlq.calls().iter().any(|c| matches!(c, Call::Send))).await; + assert!(fake.deletes().is_empty()); + dlq.fail_sends.store(false, SeqCst); + until(|| !fake.deletes().is_empty()).await; + assert_eq!( + stats.started.load(SeqCst), + 1, + "exhausted redelivery must not run again" + ); + assert_eq!(dlq.msgs.lock().unwrap().len(), 1); + stop(token, handle).await; +} + +#[tokio::test] +async fn retry_limit_requires_distinct_dead_letter_queue() { + let (_, fake, mut worker) = setup(WorkerConfig { + retry: RetryPolicy { + max_attempts: Some(1), + ..RetryPolicy::default() + }, + ..WorkerConfig::default() + }); + worker.set_dead_letter(fake.clone()); + assert!(matches!( + worker.run(CancellationToken::new()).await, + Err(Error::InvalidConfig(_)) + )); + assert_eq!(fake.receives(), 0); + let (_, fake, worker) = setup(WorkerConfig { + retry: RetryPolicy { + max_attempts: Some(1), + ..RetryPolicy::default() + }, + ..WorkerConfig::default() + }); + assert!(matches!( + worker.run(CancellationToken::new()).await, + Err(Error::InvalidConfig(_)) + )); + assert_eq!(fake.receives(), 0); +} + +#[tokio::test(start_paused = true)] +async fn panic_is_treated_as_error() { + let (_, fake, worker) = setup(WorkerConfig::default()); + let panicked = fake.push_mode(&Mode::Panic, 0); + let (token, handle) = start(worker); + until(|| !fake.extends().is_empty()).await; + assert_eq!(fake.extends()[0].0, panicked); + assert_eq!(fake.extends()[0].1, Duration::from_secs(5)); + + let ok = fake.push_mode(&Mode::Done, 0); + until(|| !fake.deletes().is_empty()).await; + assert_eq!(fake.deletes(), [ok]); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn undecodable_messages_are_retried() { + let (stats, fake, worker) = setup(WorkerConfig::default()); + fake.push("not json".into(), 0); + fake.push(r#"{"unexpected":true}"#.into(), 0); + let (token, handle) = start(worker); + until(|| fake.counts().iter().all(|c| *c == 1)).await; + until(|| fake.extends().len() == 2).await; + assert!(fake.deletes().is_empty()); + assert_eq!(stats.started.load(SeqCst), 0); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn without_heartbeat_visibility_expiry_cancels_job() { + let (stats, fake, worker) = setup(WorkerConfig { + concurrency: 1, + visibility: Duration::from_secs(2), + ..WorkerConfig::default() + }); + fake.push_mode(&Mode::UntilCancel, 0); + let (token, handle) = start(worker); + until(|| stats.cancelled.load(SeqCst) > 0).await; + assert!(fake.extends().is_empty()); + assert!(fake.deletes().is_empty()); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn heartbeat_extends_at_half_visibility() { + let (_, fake, worker) = setup(WorkerConfig { + auto_heartbeat: true, + execution_timeout: Some(Duration::from_secs(60)), + visibility: Duration::from_secs(4), + ..WorkerConfig::default() + }); + let r = fake.push_mode(&Mode::Sleep(7000), 0); + let (token, handle) = start(worker); + until(|| !fake.deletes().is_empty()).await; + let extends = fake.extends(); + assert_eq!(extends.len(), 3); + for (receipt, d, _) in &extends { + assert_eq!((receipt, *d), (&r, Duration::from_secs(4))); + } + for pair in extends.windows(2) { + assert_eq!(pair[1].2 - pair[0].2, Duration::from_secs(2)); + } + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn timeout_signals_job_and_honors_completion() { + let (stats, fake, worker) = setup(WorkerConfig { + execution_timeout: Some(Duration::from_secs(3)), + ..WorkerConfig::default() + }); + let receipt = fake.push_mode(&Mode::DoneOnCancel, 0); + let (token, handle) = start(worker); + until(|| !fake.deletes().is_empty()).await; + assert_eq!(stats.cancelled.load(SeqCst), 1); + assert_eq!(fake.deletes(), [receipt]); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn timeout_aborts_stuck_job_and_retries_after_heartbeat() { + let (stats, fake, worker) = setup(WorkerConfig { + auto_heartbeat: true, + concurrency: 1, + visibility: Duration::from_secs(4), + execution_timeout: Some(Duration::from_secs(1)), + shutdown_grace: Duration::from_secs(2), + ..WorkerConfig::default() + }); + fake.extend_delay_ms.store(1500, SeqCst); + let receipt = fake.push_mode(&Mode::Ignore, 0); + let (token, handle) = start(worker); + until(|| fake.extends().len() == 2).await; + let extends = fake.extends(); + assert_eq!( + (extends[0].0.as_str(), extends[0].1), + (receipt.as_str(), Duration::from_secs(4)) + ); + assert_eq!( + (extends[1].0.as_str(), extends[1].1), + (receipt.as_str(), Duration::from_secs(5)) + ); + assert_eq!(stats.exited.load(SeqCst), 1); + assert!(fake.deletes().is_empty()); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn timeout_on_last_attempt_dead_letters() { + let (stats, fake, mut worker) = setup(WorkerConfig { + execution_timeout: Some(S1), + shutdown_grace: S1, + retry: RetryPolicy { + max_attempts: Some(1), + ..RetryPolicy::default() + }, + ..WorkerConfig::default() + }); + let dlq = Fake::new(&stats); + worker.set_dead_letter(dlq.clone()); + let receipt = fake.push_mode(&Mode::Ignore, 0); + let (token, handle) = start(worker); + until(|| !fake.deletes().is_empty()).await; + assert_eq!(fake.deletes(), [receipt]); + assert_eq!(dlq.msgs.lock().unwrap().len(), 1); + assert_eq!(stats.exited.load(SeqCst), 1); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn timeout_does_not_settle_after_lease_loss() { + let (stats, fake, worker) = setup(WorkerConfig { + auto_heartbeat: true, + concurrency: 1, + visibility: Duration::from_secs(2), + execution_timeout: Some(Duration::from_millis(500)), + shutdown_grace: Duration::from_secs(3), + ..WorkerConfig::default() + }); + fake.block_extends.store(true, SeqCst); + fake.push_mode(&Mode::Ignore, 0); + let (token, handle) = start(worker); + until(|| stats.exited.load(SeqCst) == 1).await; + assert_eq!(fake.extends().len(), 1); + assert!(fake.deletes().is_empty()); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn stale_heartbeat_cancels_job() { + let (stats, fake, worker) = setup(WorkerConfig { + auto_heartbeat: true, + execution_timeout: Some(Duration::from_secs(60)), + visibility: Duration::from_secs(4), + ..WorkerConfig::default() + }); + *fake.stale.lock().unwrap() = true; + fake.push_mode(&Mode::UntilCancel, 0); + let (token, handle) = start(worker); + until(|| stats.cancelled.load(SeqCst) == 1).await; + stop(token, handle).await; + let durations: Vec<_> = fake.extends().into_iter().map(|e| e.1).collect(); + assert_eq!(durations, [Duration::from_secs(4)]); + assert!(fake.deletes().is_empty()); +} + +#[tokio::test(start_paused = true)] +async fn stale_heartbeat_ready_with_completion_is_not_settled() { + let (stats, fake, worker) = setup(WorkerConfig { + auto_heartbeat: true, + execution_timeout: Some(Duration::from_secs(60)), + concurrency: 1, + visibility: Duration::from_secs(4), + ..WorkerConfig::default() + }); + *fake.stale.lock().unwrap() = true; + fake.extend_until_exit.store(true, SeqCst); + fake.push_mode(&Mode::Sleep(3000), 0); + let (token, handle) = start(worker); + until(|| stats.exited.load(SeqCst) == 1).await; + stop(token, handle).await; + assert_eq!(fake.extends().len(), 1); + assert!(fake.deletes().is_empty()); +} + +#[tokio::test(start_paused = true)] +async fn stale_in_flight_heartbeat_prevents_retry() { + let (stats, fake, worker) = setup(WorkerConfig { + auto_heartbeat: true, + execution_timeout: Some(Duration::from_secs(60)), + concurrency: 1, + visibility: Duration::from_secs(4), + ..WorkerConfig::default() + }); + *fake.stale.lock().unwrap() = true; + fake.extend_delay_ms.store(1000, SeqCst); + fake.push_mode(&Mode::SleepRetry(2500, 10_000), 0); + let (token, handle) = start(worker); + until(|| stats.exited.load(SeqCst) == 1).await; + sleep(S1).await; + stop(token, handle).await; + assert_eq!(fake.extends().len(), 1); + assert!(fake.deletes().is_empty()); +} + +#[tokio::test(start_paused = true)] +async fn completed_job_is_settled_while_heartbeat_is_blocked() { + let (stats, fake, worker) = setup(WorkerConfig { + auto_heartbeat: true, + execution_timeout: Some(Duration::from_secs(60)), + concurrency: 1, + visibility: Duration::from_secs(2), + ..WorkerConfig::default() + }); + fake.block_extends.store(true, SeqCst); + let receipt = fake.push_mode(&Mode::Sleep(1500), 0); + let (token, handle) = start(worker); + until(|| !fake.deletes().is_empty()).await; + assert_eq!(fake.deletes(), [receipt]); + assert_eq!(stats.exited.load(SeqCst), 1); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn failed_heartbeats_cancel_at_visibility_deadline() { + let (stats, fake, worker) = setup(WorkerConfig { + auto_heartbeat: true, + execution_timeout: Some(Duration::from_secs(60)), + concurrency: 1, + visibility: Duration::from_secs(4), + ..WorkerConfig::default() + }); + fake.fail_extends.store(usize::MAX, SeqCst); + fake.push_mode(&Mode::UntilCancel, 0); + let (token, handle) = start(worker); + until(|| stats.cancelled.load(SeqCst) > 0).await; + let extends = fake.extends(); + assert_eq!(extends.len(), 2); + assert_eq!(extends[1].2 - extends[0].2, S1); + assert!(fake.deletes().is_empty()); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn transient_heartbeat_failure_is_retried() { + let (_, fake, worker) = setup(WorkerConfig { + auto_heartbeat: true, + execution_timeout: Some(Duration::from_secs(60)), + concurrency: 1, + visibility: Duration::from_secs(4), + ..WorkerConfig::default() + }); + fake.fail_extends.store(1, SeqCst); + let r = fake.push_mode(&Mode::Sleep(10_000), 0); + let (token, handle) = start(worker); + until(|| !fake.deletes().is_empty()).await; + assert_eq!(fake.deletes(), [r]); + let extends = fake.extends(); + assert!(extends.len() >= 3); + assert_eq!(extends[1].2 - extends[0].2, S1); + for pair in extends[1..].windows(2) { + assert_eq!(pair[1].2 - pair[0].2, Duration::from_secs(2)); + } + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn slow_heartbeats_keep_the_lease() { + let (_, fake, worker) = setup(WorkerConfig { + auto_heartbeat: true, + execution_timeout: Some(Duration::from_secs(60)), + concurrency: 1, + visibility: Duration::from_secs(4), + ..WorkerConfig::default() + }); + fake.extend_delay_ms.store(1500, SeqCst); + let r = fake.push_mode(&Mode::Sleep(9000), 0); + let (token, handle) = start(worker); + until(|| !fake.deletes().is_empty()).await; + assert_eq!(fake.deletes(), [r]); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn retry_waits_for_in_flight_heartbeat() { + let (_, fake, worker) = setup(WorkerConfig { + auto_heartbeat: true, + execution_timeout: Some(Duration::from_secs(60)), + concurrency: 1, + visibility: Duration::from_secs(4), + ..WorkerConfig::default() + }); + fake.extend_delay_ms.store(1000, SeqCst); + fake.push_mode(&Mode::SleepRetry(2500, 10_000), 0); + let (token, handle) = start(worker); + until(|| fake.extends().len() == 2).await; + let extends = fake.extends(); + assert_eq!(extends[0].1, Duration::from_secs(4)); + assert_eq!(extends[1].1, Duration::from_secs(10)); + assert_eq!(extends[1].2 - extends[0].2, S1); + assert!(fake.deletes().is_empty()); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn blocked_heartbeat_cancels_at_visibility_deadline() { + let (stats, fake, worker) = setup(WorkerConfig { + auto_heartbeat: true, + execution_timeout: Some(Duration::from_secs(60)), + concurrency: 1, + visibility: Duration::from_secs(2), + ..WorkerConfig::default() + }); + fake.block_extends.store(true, SeqCst); + fake.push_mode(&Mode::UntilCancel, 0); + let (token, handle) = start(worker); + until(|| stats.cancelled.load(SeqCst) > 0).await; + assert_eq!(fake.extends().len(), 1); + assert!(fake.deletes().is_empty()); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn uncooperative_job_is_aborted_after_lease_loss() { + let (stats, fake, worker) = setup(WorkerConfig { + auto_heartbeat: true, + execution_timeout: Some(Duration::from_secs(60)), + concurrency: 1, + visibility: Duration::from_secs(2), + shutdown_grace: Duration::from_secs(3), + ..WorkerConfig::default() + }); + fake.block_extends.store(true, SeqCst); + fake.push_mode(&Mode::Ignore, 0); + let began = Instant::now(); + let (token, handle) = start(worker); + until(|| stats.started.load(SeqCst) == 2).await; + let elapsed = began.elapsed(); + assert!(elapsed >= Duration::from_secs(5) && elapsed < Duration::from_secs(6)); + assert_eq!(stats.exited.load(SeqCst), 1); + assert!(fake.deletes().is_empty()); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn completion_after_visibility_deadline_is_not_acknowledged() { + let (stats, fake, worker) = setup(WorkerConfig { + auto_heartbeat: true, + execution_timeout: Some(Duration::from_secs(60)), + concurrency: 1, + visibility: Duration::from_secs(2), + ..WorkerConfig::default() + }); + fake.block_extends.store(true, SeqCst); + fake.push_mode(&Mode::Sleep(2000), 0); + let (token, handle) = start(worker); + until(|| stats.exited.load(SeqCst) > 0).await; + assert!(fake.deletes().is_empty()); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn heartbeat_respects_remaining_receive_window() { + let (stats, fake, worker) = setup(WorkerConfig { + auto_heartbeat: true, + execution_timeout: Some(Duration::from_secs(12 * 3600)), + concurrency: 1, + visibility: Duration::from_secs(12 * 3600), + ..WorkerConfig::default() + }); + fake.push_mode(&Mode::Sleep(6 * 3600 * 1000 + 1000), 0); + let (token, handle) = start(worker); + until(|| stats.started.load(SeqCst) == 1).await; + tokio::time::advance(Duration::from_secs(6 * 3600)).await; + until(|| !fake.extends().is_empty()).await; + tokio::time::advance(Duration::from_secs(1)).await; + until(|| !fake.deletes().is_empty()).await; + assert_eq!(fake.extends().len(), 1); + let duration = fake.extends()[0].1; + assert!(duration >= Duration::from_secs(6 * 3600 - 6)); + assert!(duration <= Duration::from_secs(6 * 3600 - 5)); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn excessive_retry_is_clamped_to_receive_window() { + let (stats, fake, worker) = setup(WorkerConfig::default()); + let receipt = fake.push_mode(&Mode::Retry(12 * 3600 * 1000), 0); + let (token, handle) = start(worker); + until(|| stats.exited.load(SeqCst) == 1).await; + sleep(Duration::from_millis(100)).await; + let extends = fake.extends(); + assert_eq!(extends.len(), 1); + assert_eq!(extends[0].0, receipt); + assert_eq!(extends[0].1, Duration::from_secs(11 * 3600)); + assert!(fake.deletes().is_empty()); + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn shutdown_cancels_jobs_and_stops_receiving() { + let (stats, fake, worker) = setup(WorkerConfig::default()); + let r = fake.push_mode(&Mode::UntilCancel, 0); + let (token, handle) = start(worker); + until(|| stats.started.load(SeqCst) == 1).await; + let receives = fake.receives(); + token.cancel(); + handle.await.unwrap().unwrap(); + assert_eq!(fake.receives(), receives); + assert_eq!(stats.cancelled.load(SeqCst), 1); + let extends = fake.extends(); + assert_eq!( + (extends[0].0.as_str(), extends[0].1), + (r.as_str(), Duration::ZERO) + ); +} + +#[tokio::test(start_paused = true)] +async fn shutdown_grace_aborts_stuck_jobs() { + let (stats, fake, worker) = setup(WorkerConfig { + shutdown_grace: Duration::from_secs(3), + ..WorkerConfig::default() + }); + fake.push_mode(&Mode::Ignore, 0); + let (token, handle) = start(worker); + until(|| stats.started.load(SeqCst) == 1).await; + let began = Instant::now(); + token.cancel(); + handle.await.unwrap().unwrap(); + let elapsed = began.elapsed(); + assert!(elapsed >= Duration::from_secs(3) && elapsed < Duration::from_secs(4)); + sleep(Duration::from_millis(1)).await; + assert_eq!(stats.exited.load(SeqCst), 1); + assert!(fake.deletes().is_empty() && fake.extends().is_empty()); +} + +#[tokio::test(start_paused = true)] +async fn concurrency_is_bounded() { + let (stats, fake, worker) = setup(WorkerConfig { + concurrency: 3, + ..WorkerConfig::default() + }); + for _ in 0..12 { + fake.push_mode(&Mode::Sleep(1000), 0); + } + let (token, handle) = start(worker); + until(|| fake.deletes().len() == 12).await; + assert_eq!(stats.max_running.load(SeqCst), 3); + let mut first = true; + for call in fake.calls() { + if let Call::Receive { max, running } = call { + assert!(max + running <= 3, "max {max} with {running} running"); + if std::mem::take(&mut first) { + assert_eq!(max, 3); + } + } + } + stop(token, handle).await; +} + +#[tokio::test(start_paused = true)] +async fn receive_errors_do_not_end_run() { + let (_, fake, worker) = setup(WorkerConfig::default()); + fake.fail_receives.store(2, SeqCst); + fake.push_mode(&Mode::Done, 0); + let (token, handle) = start(worker); + until(|| !fake.deletes().is_empty()).await; + assert!(!handle.is_finished()); + stop(token, handle).await; +} + +#[test] +#[should_panic(expected = "already registered")] +fn duplicate_register_panics() { + let (stats, _, mut worker) = setup(WorkerConfig::default()); + worker.register(Probe(stats)); +} + +#[test] +fn invalid_config_is_rejected() { + let d = WorkerConfig::default; + let secs = Duration::from_secs; + let bad = [ + WorkerConfig { + retry: RetryPolicy { + max_attempts: Some(0), + ..RetryPolicy::default() + }, + ..d() + }, + WorkerConfig { + retry: RetryPolicy { + base: secs(10), + max: Some(secs(5)), + ..RetryPolicy::default() + }, + ..d() + }, + WorkerConfig { + concurrency: 0, + ..d() + }, + WorkerConfig { + concurrency: Semaphore::MAX_PERMITS + 1, + ..d() + }, + WorkerConfig { batch: 0, ..d() }, + WorkerConfig { batch: 11, ..d() }, + WorkerConfig { + wait: Duration::ZERO, + ..d() + }, + WorkerConfig { + wait: secs(21), + ..d() + }, + WorkerConfig { + wait: Duration::from_millis(1500), + ..d() + }, + WorkerConfig { + visibility: secs(1), + ..d() + }, + WorkerConfig { + visibility: Duration::from_millis(2500), + ..d() + }, + WorkerConfig { + visibility: secs(12 * 3600 + 1), + ..d() + }, + WorkerConfig { + execution_timeout: Some(Duration::ZERO), + ..d() + }, + WorkerConfig { + execution_timeout: Some(Duration::MAX), + ..d() + }, + WorkerConfig { + auto_heartbeat: true, + ..d() + }, + ]; + let stats = Arc::new(Stats::default()); + for config in bad { + let result = Worker::new(Fake::new(&stats), config); + assert!(matches!(result, Err(Error::InvalidConfig(_)))); + } +} diff --git a/rust/crates/queue/src/lib.rs b/rust/crates/queue/src/lib.rs index fbff50dbe..43da26524 100644 --- a/rust/crates/queue/src/lib.rs +++ b/rust/crates/queue/src/lib.rs @@ -1,17 +1,29 @@ -use std::time::Duration; +use std::{collections::HashMap, time::Duration}; pub mod sqs; const MAX_RECEIVE: usize = 10; const MAX_WAIT_SECS: u64 = 20; -const MAX_DELAY_SECS: u64 = 15 * 60; const MAX_VISIBILITY_SECS: u64 = 12 * 60 * 60; +/// A transport message attribute. SQS string and number values use `Text`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MessageAttribute { + pub data_type: String, + pub value: AttributeValue, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AttributeValue { + Text(String), + Binary(Vec), +} + #[derive(Debug, Clone)] pub struct Outgoing { pub body: String, - pub delay: Duration, pub group_id: Option, + pub attributes: HashMap, } #[derive(Debug, Clone)] @@ -20,6 +32,7 @@ pub struct Received { pub body: String, pub receive_count: u32, pub group_id: Option, + pub attributes: HashMap, } pub trait Transport { @@ -27,7 +40,6 @@ pub trait Transport { /// Unknown outcomes may have succeeded; retrying them can produce duplicates. /// The underlying client may also retry requests, so a failed entry in the final /// response does not rule out success in an earlier attempt. - /// Durations must be whole seconds. fn send(&self, messages: &[Outgoing]) -> impl Future> + Send; /// Claim up to `max` messages (1..=10), long-polling up to `wait` (<= 20 s). Claimed messages are /// invisible for `visibility` (0 s ..= 12 h) and have receive_count incremented. @@ -106,16 +118,6 @@ pub enum Error { Sqs(Box), } -pub(crate) fn check_send(messages: &[Outgoing]) -> Result<(), Error> { - if messages.iter().any(|m| m.delay.subsec_nanos() != 0) { - return Err(Error::InvalidArgument("delay must be whole seconds")); - } - if messages.iter().any(|m| m.delay.as_secs() > MAX_DELAY_SECS) { - return Err(Error::InvalidArgument("delay exceeds 15 minutes")); - } - Ok(()) -} - pub(crate) fn check_receive(max: usize, wait: Duration, visibility: Duration) -> Result<(), Error> { if !(1..=MAX_RECEIVE).contains(&max) { return Err(Error::InvalidArgument("max must be 1..=10")); diff --git a/rust/crates/queue/src/sqs.rs b/rust/crates/queue/src/sqs.rs index 26c5a9901..7ba219c0a 100644 --- a/rust/crates/queue/src/sqs.rs +++ b/rust/crates/queue/src/sqs.rs @@ -3,15 +3,16 @@ use std::time::Duration; use aws_sdk_sqs::{ Client, error::ProvideErrorMetadata, + primitives::Blob, types::{ - DeleteMessageBatchRequestEntry, Message, MessageSystemAttributeName, + DeleteMessageBatchRequestEntry, Message, MessageAttributeValue, MessageSystemAttributeName, SendMessageBatchRequestEntry, }, }; use crate::{ - BatchError, BatchOutcome, Error, Outgoing, Received, Transport, check_receive, check_send, - check_visibility, + AttributeValue, BatchError, BatchOutcome, Error, MessageAttribute, Outgoing, Received, + Transport, check_receive, check_visibility, }; const BATCH: usize = 10; @@ -96,14 +97,47 @@ fn received(m: &Message) -> Result { group_id: attrs .and_then(|a| a.get(&MessageSystemAttributeName::MessageGroupId)) .cloned(), + attributes: m + .message_attributes() + .into_iter() + .flat_map(|attrs| attrs.iter()) + .map(|(name, attr)| { + let value = match (attr.string_value(), attr.binary_value()) { + (Some(text), None) => AttributeValue::Text(text.to_owned()), + (None, Some(bytes)) => AttributeValue::Binary(bytes.as_ref().to_vec()), + _ => return Err(Error::InvalidResponse("invalid message attribute value")), + }; + Ok(( + name.clone(), + MessageAttribute { + data_type: attr.data_type().to_owned(), + value, + }, + )) + }) + .collect::>()?, }) } +fn message_size(message: &Outgoing) -> usize { + message + .attributes + .iter() + .fold(message.body.len(), |size, (name, attribute)| { + let value_len = match &attribute.value { + AttributeValue::Text(text) => text.len(), + AttributeValue::Binary(bytes) => bytes.len(), + }; + size.saturating_add(name.len()) + .saturating_add(attribute.data_type.len()) + .saturating_add(value_len) + }) +} + impl Transport for SqsQueue { async fn send(&self, messages: &[Outgoing]) -> Result<(), Error> { - check_send(messages)?; - if messages.iter().any(|m| m.body.len() > MAX_BATCH_BYTES) { - return Err(Error::InvalidArgument("message body exceeds 1 MiB")); + if messages.iter().any(|m| message_size(m) > MAX_BATCH_BYTES) { + return Err(Error::InvalidArgument("message exceeds 1 MiB")); } let mut outcomes = vec![BatchOutcome::NotAttempted; messages.len()]; let mut start = 0; @@ -111,7 +145,7 @@ impl Transport for SqsQueue { let mut end = start; let mut bytes = 0; while end < messages.len() && end - start < BATCH { - let size = messages[end].body.len(); + let size = message_size(&messages[end]); if size > MAX_BATCH_BYTES - bytes { break; } @@ -125,11 +159,21 @@ impl Transport for SqsQueue { .map(|(i, m)| { let mut e = SendMessageBatchRequestEntry::builder() .id((start + i).to_string()) - .message_body(&m.body) - .delay_seconds(secs(m.delay)); + .message_body(&m.body); if let Some(g) = &m.group_id { e = e.message_group_id(g); } + for (name, attr) in &m.attributes { + let value = MessageAttributeValue::builder().data_type(&attr.data_type); + let value = match &attr.value { + AttributeValue::Text(text) => value.string_value(text), + AttributeValue::Binary(bytes) => { + value.binary_value(Blob::new(bytes.clone())) + } + } + .build()?; + e = e.message_attributes(name, value); + } e.build() }) .collect::, _>>() @@ -199,6 +243,7 @@ impl Transport for SqsQueue { .visibility_timeout(secs(visibility)) .message_system_attribute_names(MessageSystemAttributeName::ApproximateReceiveCount) .message_system_attribute_names(MessageSystemAttributeName::MessageGroupId) + .message_attribute_names("All") .send() .await .map_err(sqs)?; diff --git a/rust/crates/queue/tests/contract.rs b/rust/crates/queue/tests/contract.rs index aacd5efab..a85a065f5 100644 --- a/rust/crates/queue/tests/contract.rs +++ b/rust/crates/queue/tests/contract.rs @@ -12,7 +12,10 @@ use aws_sdk_sqs::{ config::{BehaviorVersion, Credentials, Region}, types::QueueAttributeName, }; -use storage_queue::{BatchOutcome, Error, Outgoing, Received, Transport, sqs::SqsQueue}; +use storage_queue::{ + AttributeValue, BatchOutcome, Error, MessageAttribute, Outgoing, Received, Transport, + sqs::SqsQueue, +}; use tokio::time::sleep; const SQS_ENDPOINT: &str = "STORAGE_QUEUE_TEST_SQS_ENDPOINT"; @@ -96,8 +99,8 @@ macro_rules! sqs_contract { fn msg(body: &str) -> Outgoing { Outgoing { body: body.into(), - delay: Duration::ZERO, group_id: None, + attributes: Default::default(), } } @@ -116,10 +119,26 @@ async fn assert_empty(q: &T) { } async fn round_trip(q: &T) { + let attributes = std::collections::HashMap::from([ + ( + "queue.key".into(), + MessageAttribute { + data_type: "String".into(), + value: AttributeValue::Text("g1".into()), + }, + ), + ( + "binary".into(), + MessageAttribute { + data_type: "Binary.custom".into(), + value: AttributeValue::Binary(vec![0, 1, 255]), + }, + ), + ]); q.send(&[Outgoing { body: "hello".into(), - delay: NOW, group_id: Some("g1".into()), + attributes: attributes.clone(), }]) .await .unwrap(); @@ -127,6 +146,7 @@ async fn round_trip(q: &T) { assert_eq!(got.body, "hello"); assert_eq!(got.receive_count, 1); assert_eq!(got.group_id.as_deref(), Some("g1")); + assert_eq!(got.attributes, attributes); } sqs_contract!(round_trip); @@ -187,41 +207,6 @@ async fn stale_receipt(q: &T) { } sqs_contract!(stale_receipt); -async fn delay(q: &T) { - q.send(&[Outgoing { - delay: S2, - ..msg("a") - }]) - .await - .unwrap(); - assert_empty(q).await; - sleep(Duration::from_millis(2500)).await; - assert_eq!(receive_one(q, S2).await.body, "a"); -} -sqs_contract!(delay); - -#[tokio::test] -#[ignore = "requires an SQS-compatible endpoint"] -async fn zero_delay_overrides_queue_default() { - let endpoint = - std::env::var(SQS_ENDPOINT).expect("STORAGE_QUEUE_TEST_SQS_ENDPOINT must be set"); - let client = sqs_client(&endpoint); - let url = client - .create_queue() - .queue_name(unique("default-delay")) - .attributes(QueueAttributeName::DelaySeconds, "10") - .send() - .await - .unwrap() - .queue_url - .unwrap(); - let q = SqsQueue::new(client, url); - q.send(&[msg("immediate")]).await.unwrap(); - let got = q.receive(1, S1, S2).await.unwrap(); - assert_eq!(got.len(), 1); - assert_eq!(got[0].body, "immediate"); -} - async fn chunked_send(q: &T) { let all: Vec<_> = (0..25).map(|i| msg(&format!("m{i}"))).collect(); q.send(&all).await.unwrap(); @@ -307,24 +292,6 @@ async fn validation(q: &T) { .map(drop)); bad(q.extend("r", Duration::from_secs(13 * 3600)).await); bad(q.extend("r", Duration::from_millis(500)).await); - bad(q - .send(&[Outgoing { - delay: Duration::from_millis(500), - ..msg("a") - }]) - .await); - bad(q - .send(&[Outgoing { - delay: Duration::from_millis(900_001), - ..msg("a") - }]) - .await); - bad(q - .send(&[Outgoing { - delay: Duration::from_secs(16 * 60), - ..msg("a") - }]) - .await); } #[tokio::test] diff --git a/rust/crates/queue/tests/failure_paths.rs b/rust/crates/queue/tests/failure_paths.rs index 6356f897f..8f03fe795 100644 --- a/rust/crates/queue/tests/failure_paths.rs +++ b/rust/crates/queue/tests/failure_paths.rs @@ -9,7 +9,9 @@ use aws_sdk_sqs::{ Client, config::{BehaviorVersion, Credentials, Region, retry::RetryConfig}, }; -use storage_queue::{BatchOutcome, Error, Outgoing, Transport, sqs::SqsQueue}; +use storage_queue::{ + AttributeValue, BatchOutcome, Error, MessageAttribute, Outgoing, Transport, sqs::SqsQueue, +}; // A small HTTP endpoint exercises the SDK and transport without depending on emulator failure injection. fn endpoint(responses: Vec<(u16, String)>) -> (SqsQueue, thread::JoinHandle>) { @@ -71,8 +73,8 @@ fn messages(n: usize) -> Vec { (0..n) .map(|_| Outgoing { body: "body".into(), - delay: Duration::ZERO, group_id: None, + attributes: Default::default(), }) .collect() } @@ -167,7 +169,7 @@ async fn delete_reports_invalid_receipts_and_other_rejections() { } #[tokio::test] -async fn send_splits_on_utf8_bytes_and_explicitly_sends_zero_delay() { +async fn send_splits_on_utf8_bytes() { let responses = vec![ ( 200, @@ -182,18 +184,18 @@ async fn send_splits_on_utf8_bytes_and_explicitly_sends_zero_delay() { let input = vec![ Outgoing { body: "é".repeat(262_144), - delay: Duration::ZERO, group_id: None, + attributes: Default::default(), }, Outgoing { body: "x".repeat(524_288), - delay: Duration::from_secs(3), group_id: None, + attributes: Default::default(), }, Outgoing { body: "z".into(), - delay: Duration::ZERO, group_id: None, + attributes: Default::default(), }, ]; queue.send(&input).await.unwrap(); @@ -202,10 +204,7 @@ async fn send_splits_on_utf8_bytes_and_explicitly_sends_zero_delay() { assert!(requests[0].contains(r#""Id":"0""#)); assert!(requests[0].contains(r#""Id":"1""#)); assert!(!requests[0].contains(r#""Id":"2""#)); - assert!(requests[0].contains(r#""DelaySeconds":0"#)); - assert!(requests[0].contains(r#""DelaySeconds":3"#)); assert!(requests[1].contains(r#""Id":"2""#)); - assert!(requests[1].contains(r#""DelaySeconds":0"#)); } #[tokio::test] @@ -215,7 +214,26 @@ async fn oversized_message_is_rejected_before_any_send() { input[1].body = "x".repeat(1_048_577); assert!(matches!( queue.send(&input).await, - Err(Error::InvalidArgument("message body exceeds 1 MiB")) + Err(Error::InvalidArgument("message exceeds 1 MiB")) + )); + assert!(server.join().unwrap().is_empty()); +} + +#[tokio::test] +async fn attribute_bytes_count_towards_message_limit() { + let (queue, server) = endpoint(vec![]); + let mut input = messages(1); + input[0].body = "x".repeat(1_048_570); + input[0].attributes.insert( + "queue.key".into(), + MessageAttribute { + data_type: "String".into(), + value: AttributeValue::Text("tenant".into()), + }, + ); + assert!(matches!( + queue.send(&input).await, + Err(Error::InvalidArgument("message exceeds 1 MiB")) )); assert!(server.join().unwrap().is_empty()); } diff --git a/src/internal/queue/event.test.ts b/src/internal/queue/event.test.ts index 24c746f06..20e2a3f7e 100644 --- a/src/internal/queue/event.test.ts +++ b/src/internal/queue/event.test.ts @@ -1,3 +1,5 @@ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' import { queueJobSchedulingTime } from '@internal/monitoring/metrics' import { vi } from 'vitest' @@ -55,6 +57,27 @@ describe('Event payload versioning', () => { vi.resetModules() }) + it('matches the shared Node and Rust job payload fixture', async () => { + const { eventModule, queueModule } = await loadQueueModules({ pgQueueEnable: true }) + const TestEvent = defineTestEvent(eventModule.Event) + const insert = vi.fn().mockResolvedValue('job-id') + vi.spyOn(queueModule.Queue, 'getInstance').mockReturnValue({ insert } as unknown as ReturnType< + typeof queueModule.Queue.getInstance + >) + + await TestEvent.batchSend([new TestEvent(createPayload())]) + + const fixture = JSON.parse( + readFileSync( + join(__dirname, '../../../rust/crates/jobs/tests/fixtures/node-payload.json'), + 'utf8' + ) + ) + expect(insert.mock.calls[0][0][0]).toEqual( + expect.objectContaining({ name: 'test-event', data: fixture }) + ) + }) + it('does not mutate payloads passed to static send', async () => { const { eventModule } = await loadQueueModules() const TestEvent = defineTestEvent(eventModule.Event) From 6a6ef98f9dc2c2276e6b1049ebd7e6d72981fd51 Mon Sep 17 00:00:00 2001 From: Ferhat Elmas Date: Fri, 13 Nov 2026 00:38:40 +0100 Subject: [PATCH 2/4] refactor: rename for better layers Signed-off-by: Ferhat Elmas --- rust/Cargo.lock | 6 +- rust/Cargo.toml | 2 +- rust/README.md | 4 +- rust/crates/jobs/Cargo.toml | 21 - rust/crates/jobs/src/lib.rs | 765 --------------- rust/crates/queue-transport/Cargo.toml | 12 + rust/crates/queue-transport/src/lib.rs | 142 +++ .../{queue => queue-transport}/src/sqs.rs | 0 .../tests/contract.rs | 2 +- .../tests/failure_paths.rs | 2 +- rust/crates/queue/Cargo.toml | 13 +- rust/crates/queue/src/lib.rs | 871 +++++++++++++++--- .../tests/fixtures/node-payload.json | 0 rust/crates/{jobs => queue}/tests/sqs.rs | 4 +- rust/crates/{jobs => queue}/tests/worker.rs | 20 +- src/internal/queue/event.test.ts | 2 +- 16 files changed, 933 insertions(+), 933 deletions(-) delete mode 100644 rust/crates/jobs/Cargo.toml delete mode 100644 rust/crates/jobs/src/lib.rs create mode 100644 rust/crates/queue-transport/Cargo.toml create mode 100644 rust/crates/queue-transport/src/lib.rs rename rust/crates/{queue => queue-transport}/src/sqs.rs (100%) rename rust/crates/{queue => queue-transport}/tests/contract.rs (99%) rename rust/crates/{queue => queue-transport}/tests/failure_paths.rs (99%) rename rust/crates/{jobs => queue}/tests/fixtures/node-payload.json (100%) rename rust/crates/{jobs => queue}/tests/sqs.rs (98%) rename rust/crates/{jobs => queue}/tests/worker.rs (98%) diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 547e7aa97..cb5ab3187 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1060,14 +1060,14 @@ dependencies = [ ] [[package]] -name = "storage-jobs" +name = "storage-queue" version = "0.1.0" dependencies = [ "aws-sdk-sqs", "serde", "serde_json", "sha2", - "storage-queue", + "storage-queue-transport", "thiserror", "tokio", "tokio-util", @@ -1075,7 +1075,7 @@ dependencies = [ ] [[package]] -name = "storage-queue" +name = "storage-queue-transport" version = "0.1.0" dependencies = [ "aws-sdk-sqs", diff --git a/rust/Cargo.toml b/rust/Cargo.toml index d5b1c0c7a..f6ad84e99 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "3" -members = ["crates/queue", "crates/jobs"] +members = ["crates/queue-transport", "crates/queue"] [workspace.dependencies] aws-sdk-sqs = { version = "1.119.0", default-features = false, features = ["behavior-version-latest", "default-https-client", "rt-tokio"] } diff --git a/rust/README.md b/rust/README.md index 1ef6f0b33..d046ff9ab 100644 --- a/rust/README.md +++ b/rust/README.md @@ -1,7 +1,7 @@ # Rust workspace -`crates/queue` provides queue transport primitives, currently backed by SQS standard queues. -`crates/jobs` provides JSON job dispatch, bounded concurrency, visibility heartbeats, retries, +`crates/queue-transport` provides queue transport primitives, currently backed by SQS standard queues. +`crates/queue` provides JSON job dispatch, bounded concurrency, visibility heartbeats, retries, and graceful shutdown. Jobs use the Node queue manager's bare JSON payload and message attributes. Each worker handles diff --git a/rust/crates/jobs/Cargo.toml b/rust/crates/jobs/Cargo.toml deleted file mode 100644 index b0c3c8bcb..000000000 --- a/rust/crates/jobs/Cargo.toml +++ /dev/null @@ -1,21 +0,0 @@ -[package] -name = "storage-jobs" -version = "0.1.0" -edition = "2024" - -[lib] -name = "storage_jobs" - -[dependencies] -serde.workspace = true -serde_json.workspace = true -sha2.workspace = true -storage-queue = { path = "../queue" } -thiserror.workspace = true -tokio = { workspace = true, features = ["sync"] } -tokio-util.workspace = true -tracing.workspace = true - -[dev-dependencies] -aws-sdk-sqs.workspace = true -tokio = { workspace = true, features = ["test-util"] } diff --git a/rust/crates/jobs/src/lib.rs b/rust/crates/jobs/src/lib.rs deleted file mode 100644 index 1c987485b..000000000 --- a/rust/crates/jobs/src/lib.rs +++ /dev/null @@ -1,765 +0,0 @@ -use std::{collections::HashMap, future::Future, pin::Pin, sync::Arc, time::Duration}; - -use serde::{Serialize, de::DeserializeOwned}; -use serde_json::value::RawValue; -use sha2::{Digest, Sha256}; -use storage_queue::{AttributeValue, MessageAttribute, Outgoing, Received, Transport}; -use tokio::{ - sync::Semaphore, - task::{JoinHandle, JoinSet}, - time::{self, Instant}, -}; -use tokio_util::sync::CancellationToken; -use tracing::{Instrument, error, info_span, warn}; - -pub type BoxError = Box; -type BoxFuture = Pin + Send>>; -type Heartbeat<'a> = ( - Instant, - Duration, - Pin> + Send + 'a>>, -); - -const SYSTEM_TENANT_REF: &str = "SYSTEM_TENANT"; -const HEADERS_ATTRIBUTE: &str = "queue.headers"; -const KEY_ATTRIBUTE: &str = "queue.key"; -const MAX_BATCH: usize = 10; -const MAX_WAIT: Duration = Duration::from_secs(20); -const MAX_VISIBILITY: Duration = Duration::from_secs(12 * 60 * 60); -// Matches the Node SQS adapter's cap on parked retries. -const MAX_RETRY_DELAY: Duration = Duration::from_secs(11 * 60 * 60); -// Leave time for the visibility request to reach SQS before its 12-hour deadline. -const VISIBILITY_MARGIN: Duration = Duration::from_secs(5); -const RECEIVE_RETRY_DELAY: Duration = Duration::from_secs(1); -const HEARTBEAT_RETRY: Duration = Duration::from_secs(1); - -#[derive(Debug, thiserror::Error)] -pub enum Error { - #[error("invalid config: {0}")] - InvalidConfig(&'static str), - #[error("encode failed: {0}")] - Encode(#[from] serde_json::Error), -} - -pub trait Job: Send + Sync + 'static { - /// Queue name used by the Node manager's registry. - const NAME: &'static str; - /// Optional manager message type, carried in `queue.headers`. - const TYPE: Option<&'static str> = None; - type Payload: Serialize + DeserializeOwned + Send + 'static; - fn run( - &self, - ctx: Context, - payload: Self::Payload, - ) -> impl Future> + Send; -} - -pub struct Context { - pub tenant: Option, - pub receive_count: u32, - pub key: Option, - pub headers: HashMap, - /// Fires on timeout, shutdown, or when the message lease is lost. - pub cancel: CancellationToken, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Disposition { - Done, - /// Retry using the current receipt's visibility timeout. SQS cannot guarantee - /// delays beyond the remaining 12-hour receive window. - RetryAfter(Duration), -} - -fn payload_tenant(payload: &RawValue) -> Option { - let value = serde_json::from_str::(payload.get()).ok()?; - value.get("tenant")?.get("ref")?.as_str().map(str::to_owned) -} - -fn string_attribute(value: String) -> MessageAttribute { - MessageAttribute { - data_type: "String".into(), - value: AttributeValue::Text(value), - } -} - -fn group_id(key: &str) -> String { - if !key.is_empty() && key.len() <= 128 && key.bytes().all(|b| (0x21..=0x7e).contains(&b)) { - key.to_owned() - } else { - use std::fmt::Write; - let mut result = String::from("sha256:"); - for byte in Sha256::digest(key.as_bytes()) { - write!(&mut result, "{byte:02x}").expect("writing to a string cannot fail"); - } - result - } -} - -#[derive(Debug, Default)] -pub struct EncodeOptions<'a> { - /// Override the key derived from the payload's tenant reference. - pub key: Option<&'a str>, - /// Used as a fair-queue group when there is no key. Standard SQS does not deduplicate it. - pub idempotency_key: Option<&'a str>, - pub headers: HashMap, -} - -/// Encode the bare JSON body and manager attributes for this job's queue. -pub fn encode(payload: &J::Payload) -> Result { - encode_with_options::(payload, EncodeOptions::default()) -} - -pub fn encode_with_options( - payload: &J::Payload, - options: EncodeOptions<'_>, -) -> Result { - let payload = serde_json::value::to_raw_value(payload)?; - let tenant = payload_tenant(&payload).filter(|t| t != SYSTEM_TENANT_REF); - let key = options - .key - .or(tenant.as_deref()) - .filter(|key| !key.is_empty()); - let fair_group = key.or(options.idempotency_key.filter(|key| !key.is_empty())); - let mut attributes = HashMap::new(); - if let Some(key) = key { - attributes.insert(KEY_ATTRIBUTE.into(), string_attribute(key.to_owned())); - } - let mut headers = options.headers; - if let Some(kind) = J::TYPE { - headers - .entry("message-type".into()) - .or_insert_with(|| kind.to_owned()); - } - if !headers.is_empty() { - attributes.insert( - HEADERS_ATTRIBUTE.into(), - string_attribute(serde_json::to_string(&headers)?), - ); - } - Ok(Outgoing { - body: payload.get().to_owned(), - group_id: fair_group.map(group_id), - attributes, - }) -} - -#[derive(Debug, Clone)] -pub struct WorkerConfig { - pub concurrency: usize, - pub batch: usize, - pub wait: Duration, - pub visibility: Duration, - /// Renew visibility while a job runs. Requires an execution timeout. - pub auto_heartbeat: bool, - /// Optional maximum handler runtime before cancellation. - pub execution_timeout: Option, - /// Failure retry policy for this queue. A limit requires a dead-letter transport. - pub retry: RetryPolicy, - /// How long a cancelled job may run before it is aborted. - pub shutdown_grace: Duration, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Backoff { - Fixed, - Exponential, -} - -#[derive(Debug, Clone)] -pub struct RetryPolicy { - /// Maximum deliveries, including crash redeliveries. `None` means no local limit. - pub max_attempts: Option, - pub backoff: Backoff, - pub base: Duration, - pub max: Option, -} - -impl Default for RetryPolicy { - fn default() -> Self { - Self { - max_attempts: None, - backoff: Backoff::Exponential, - base: Duration::from_secs(5), - max: Some(Duration::from_secs(300)), - } - } -} - -impl RetryPolicy { - fn delay(&self, receive_count: u32) -> Duration { - let delay = match self.backoff { - Backoff::Fixed => self.base, - Backoff::Exponential => { - let mut delay = self.base; - if !delay.is_zero() { - for _ in 0..receive_count.saturating_sub(1) { - delay = delay.saturating_mul(2); - // The SQS settle path cannot park longer than this. - if delay >= MAX_RETRY_DELAY { - break; - } - } - } - delay - } - }; - self.max.map_or(delay, |max| delay.min(max)) - } -} - -impl Default for WorkerConfig { - fn default() -> Self { - Self { - concurrency: 16, - batch: MAX_BATCH, - wait: MAX_WAIT, - visibility: Duration::from_secs(60), - auto_heartbeat: false, - execution_timeout: None, - retry: RetryPolicy::default(), - shutdown_grace: Duration::from_secs(30), - } - } -} - -impl WorkerConfig { - fn validate(&self) -> Result<(), Error> { - if !(1..=Semaphore::MAX_PERMITS).contains(&self.concurrency) { - return Err(Error::InvalidConfig( - "concurrency must be 1..=Semaphore::MAX_PERMITS", - )); - } - if !(1..=MAX_BATCH).contains(&self.batch) { - return Err(Error::InvalidConfig("batch must be 1..=10")); - } - if self.wait.subsec_nanos() != 0 || self.wait.is_zero() || self.wait > MAX_WAIT { - return Err(Error::InvalidConfig( - "wait must be whole seconds in 1..=20 s", - )); - } - if self.visibility.subsec_nanos() != 0 - || self.visibility < Duration::from_secs(2) - || self.visibility > MAX_VISIBILITY - { - return Err(Error::InvalidConfig( - "visibility must be whole seconds in 2 s..=12 h", - )); - } - if self.execution_timeout.is_some_and(|timeout| { - timeout.is_zero() || Instant::now().checked_add(timeout).is_none() - }) { - return Err(Error::InvalidConfig( - "execution_timeout must be greater than zero and representable", - )); - } - if self.auto_heartbeat && self.execution_timeout.is_none() { - return Err(Error::InvalidConfig( - "auto_heartbeat requires execution_timeout", - )); - } - if Instant::now().checked_add(self.shutdown_grace).is_none() { - return Err(Error::InvalidConfig("shutdown_grace must be representable")); - } - if self.retry.max_attempts == Some(0) { - return Err(Error::InvalidConfig("max_attempts must be at least 1")); - } - if self.retry.max.is_some_and(|max| max < self.retry.base) { - return Err(Error::InvalidConfig( - "maximum backoff must be at least the base", - )); - } - Ok(()) - } -} - -trait Handler: Send + Sync { - fn start( - &self, - ctx: Context, - payload: &RawValue, - ) -> Result>, serde_json::Error>; -} - -struct Typed(Arc); - -impl Handler for Typed { - fn start( - &self, - ctx: Context, - payload: &RawValue, - ) -> Result>, serde_json::Error> { - let payload = serde_json::from_str(payload.get())?; - let job = self.0.clone(); - Ok(Box::pin(async move { job.run(ctx, payload).await })) - } -} - -struct AbortOnDrop(JoinHandle); - -impl Drop for AbortOnDrop { - fn drop(&mut self) { - self.0.abort(); - } -} - -struct Shared { - transport: Arc, - config: WorkerConfig, - handler: Box, - queue: &'static str, - dead_letter: Option>, - jobs: CancellationToken, -} - -pub struct Worker { - transport: Arc, - config: WorkerConfig, - handler: Option<(&'static str, Box)>, - dead_letter: Option>, -} - -impl Worker { - pub fn new(transport: Arc, config: WorkerConfig) -> Result { - config.validate()?; - Ok(Self { - transport, - config, - handler: None, - dead_letter: None, - }) - } - - /// Bind the single job handled by this queue. Panics if already bound. - pub fn register(&mut self, job: J) { - assert!(self.handler.is_none(), "a job is already registered"); - self.handler = Some((J::NAME, Box::new(Typed(Arc::new(job))))); - } - - /// Supply a distinct queue for exhausted messages. Delivery to it is at least once. - pub fn set_dead_letter(&mut self, transport: Arc) { - self.dead_letter = Some(transport); - } - - pub async fn run(self, shutdown: CancellationToken) -> Result<(), Error> { - let (queue, handler) = self - .handler - .ok_or(Error::InvalidConfig("no job registered"))?; - if self.config.retry.max_attempts.is_some() && self.dead_letter.is_none() { - return Err(Error::InvalidConfig( - "max_attempts requires a dead-letter queue", - )); - } - if self - .dead_letter - .as_ref() - .is_some_and(|dlq| Arc::ptr_eq(dlq, &self.transport)) - { - return Err(Error::InvalidConfig( - "dead-letter queue must be distinct from the source", - )); - } - let grace = self.config.shutdown_grace; - let shared = Arc::new(Shared { - transport: self.transport, - config: self.config, - handler, - queue, - dead_letter: self.dead_letter, - jobs: CancellationToken::new(), - }); - let permits = Arc::new(Semaphore::new(shared.config.concurrency)); - let mut tasks = JoinSet::new(); - - while let Some(messages) = receive(&shared, &permits, &shutdown).await { - for (message, permit, received_at, receive_started) in messages { - let shared = shared.clone(); - tasks.spawn(async move { - handle(&shared, message, received_at, receive_started).await; - drop(permit); - }); - } - while tasks.try_join_next().is_some() {} - } - - shared.jobs.cancel(); - let drain = async { while tasks.join_next().await.is_some() {} }; - if time::timeout(grace, drain).await.is_err() { - warn!("shutdown grace elapsed, aborting in-flight jobs"); - } - tasks.shutdown().await; - Ok(()) - } -} - -async fn receive( - shared: &Shared, - permits: &Arc, - shutdown: &CancellationToken, -) -> Option< - Vec<( - Received, - tokio::sync::OwnedSemaphorePermit, - Instant, - Instant, - )>, -> { - let config = &shared.config; - let first = tokio::select! { - biased; - _ = shutdown.cancelled() => return None, - permit = permits.clone().acquire_owned() => permit.expect("semaphore is never closed"), - }; - let mut held = vec![first]; - while held.len() < config.batch { - match permits.clone().try_acquire_owned() { - Ok(permit) => held.push(permit), - Err(_) => break, - } - } - let receive_started = Instant::now(); - let result = tokio::select! { - biased; - _ = shutdown.cancelled() => return None, - result = shared.transport.receive(held.len(), config.wait, config.visibility) => result, - }; - match result { - Ok(messages) => { - let received_at = Instant::now(); - Some( - messages - .into_iter() - .zip(held) - .map(|(message, permit)| (message, permit, received_at, receive_started)) - .collect(), - ) - } - Err(e) => { - warn!(error = ?e, "receive failed"); - tokio::select! { - _ = shutdown.cancelled() => None, - _ = time::sleep(RECEIVE_RETRY_DELAY) => Some(Vec::new()), - } - } - } -} - -async fn handle( - shared: &Shared, - message: Received, - received_at: Instant, - receive_started: Instant, -) { - let deadline = received_at + shared.config.visibility; - if shared - .config - .retry - .max_attempts - .is_some_and(|max| message.receive_count > max) - { - if let Err(e) = dead_letter(shared, &message, deadline).await { - warn!(error = ?e, "dead-lettering failed; original message remains in the queue"); - } - return; - } - let payload = match serde_json::from_str::>(&message.body) { - Ok(payload) => payload, - Err(e) => { - warn!(error = %e, receive_count = message.receive_count, "invalid JSON payload"); - if let Err(e) = retry_later(shared, &message, receive_started, deadline).await { - warn!(error = ?e, "disposition failed"); - } - return; - } - }; - let tenant = payload_tenant(&payload); - let span = info_span!( - "job", - name = %shared.queue, - tenant = ?tenant, - receive_count = message.receive_count - ); - process( - shared, - message, - payload, - tenant, - received_at, - receive_started, - ) - .instrument(span) - .await; -} - -fn text_attribute<'a>(message: &'a Received, name: &str) -> Option<&'a str> { - match &message.attributes.get(name)?.value { - AttributeValue::Text(text) => Some(text), - AttributeValue::Binary(_) => None, - } -} - -fn message_headers(message: &Received) -> HashMap { - if let Some(packed) = text_attribute(message, HEADERS_ATTRIBUTE) { - return match serde_json::from_str::(packed) { - Ok(serde_json::Value::Object(headers)) => headers - .into_iter() - .filter_map(|(name, value)| value.as_str().map(|text| (name, text.to_owned()))) - .collect(), - _ => HashMap::new(), - }; - } - message - .attributes - .iter() - .filter_map(|(name, attribute)| { - if name.starts_with("queue.") || attribute.data_type.starts_with("Binary") { - return None; - } - match &attribute.value { - AttributeValue::Text(value) => Some((name.clone(), value.clone())), - AttributeValue::Binary(_) => None, - } - }) - .collect() -} - -async fn process( - shared: &Shared, - message: Received, - payload: Box, - tenant: Option, - received_at: Instant, - receive_started: Instant, -) { - let cancel = shared.jobs.child_token(); - let ctx = Context { - tenant, - receive_count: message.receive_count, - key: text_attribute(&message, KEY_ATTRIBUTE).map(str::to_owned), - headers: message_headers(&message), - cancel: cancel.clone(), - }; - let future = match shared.handler.start(ctx, &payload) { - Ok(future) => future, - Err(e) => { - warn!(error = %e, "invalid payload"); - if let Err(e) = retry_later( - shared, - &message, - receive_started, - received_at + shared.config.visibility, - ) - .await - { - warn!(error = ?e, "disposition failed"); - } - return; - } - }; - let execution_deadline = shared - .config - .execution_timeout - .map(|timeout| Instant::now() + timeout); - let mut job = AbortOnDrop(tokio::spawn(future.in_current_span())); - - let visibility = shared.config.visibility; - let half = visibility / 2; - let mut next_beat = received_at + half; - let mut heartbeat: Option> = None; - let mut lease_deadline = received_at + visibility; - let mut cancel_deadline = None; - let mut timed_out = false; - // Lease-loss branches precede the job so that a ready loss is never ignored. - let joined = loop { - tokio::select! { - biased; - _ = time::sleep_until(lease_deadline) => { - warn!("visibility expired, cancelling job"); - break None; - } - result = async { heartbeat.as_mut().expect("guarded").2.as_mut().await }, if heartbeat.is_some() => { - let (started, duration, _) = heartbeat.take().expect("guarded"); - match result { - Ok(()) => { - lease_deadline = started + duration; - next_beat = started + half; - } - Err(storage_queue::Error::StaleReceipt) => { - warn!("lease lost, cancelling job"); - break None; - } - Err(e) => { - warn!(error = ?e, "heartbeat failed"); - next_beat = Instant::now() + HEARTBEAT_RETRY.min(half); - } - } - } - joined = &mut job.0 => break Some(joined), - _ = async { time::sleep_until(execution_deadline.expect("guarded")).await }, if execution_deadline.is_some() && cancel_deadline.is_none() => { - warn!("job execution timed out, cancelling job"); - cancel.cancel(); - cancel_deadline = Some(Instant::now() + shared.config.shutdown_grace); - } - _ = async { time::sleep_until(cancel_deadline.expect("guarded")).await }, if cancel_deadline.is_some() => { - warn!("job ignored cancellation, aborting"); - job.0.abort(); - let joined = (&mut job.0).await; - timed_out = matches!(&joined, Err(e) if e.is_cancelled()); - break Some(joined); - } - _ = time::sleep_until(next_beat), if shared.config.auto_heartbeat && heartbeat.is_none() => { - let started = Instant::now(); - let duration = visibility.min(remaining_window(receive_started, started)); - if duration.is_zero() { - warn!("visibility window exhausted, cancelling job"); - break None; - } - heartbeat = Some(( - started, - duration, - Box::pin(shared.transport.extend(&message.receipt, duration)), - )); - } - } - }; - let Some(joined) = joined else { - // A lost lease must not settle a delivery that may now be owned elsewhere. - cancel.cancel(); - if time::timeout(shared.config.shutdown_grace, &mut job.0) - .await - .is_err() - { - warn!("job ignored cancellation, aborting"); - } - return; - }; - - if !matches!(joined, Ok(Ok(Disposition::Done))) { - // A late heartbeat would override the retry delay. - if let Some((started, duration, extend)) = heartbeat { - match time::timeout_at(lease_deadline, extend).await { - Ok(Ok(())) => lease_deadline = started + duration, - Ok(Err(storage_queue::Error::StaleReceipt)) => return, - Ok(Err(_)) | Err(_) => {} - } - } - } - if Instant::now() >= lease_deadline { - return; - } - let result = if timed_out { - if shared.jobs.is_cancelled() { - extend(shared, &message, Duration::ZERO, receive_started).await - } else { - retry_later(shared, &message, receive_started, lease_deadline).await - } - } else { - match joined { - Ok(Ok(Disposition::Done)) => shared.transport.delete(&[&message.receipt]).await, - Ok(Ok(Disposition::RetryAfter(delay))) => { - if shared.jobs.is_cancelled() { - extend(shared, &message, Duration::ZERO, receive_started).await - } else if exhausted(shared, &message) { - dead_letter(shared, &message, lease_deadline).await - } else { - extend(shared, &message, delay, receive_started).await - } - } - Ok(Err(e)) => { - error!(error = %e, "job failed"); - if shared.jobs.is_cancelled() { - extend(shared, &message, Duration::ZERO, receive_started).await - } else { - retry_later(shared, &message, receive_started, lease_deadline).await - } - } - Err(e) => { - error!(error = %e, "job panicked"); - retry_later(shared, &message, receive_started, lease_deadline).await - } - } - }; - if let Err(e) = result { - warn!(error = ?e, "disposition failed, message will reappear after visibility timeout"); - } -} - -async fn retry_later( - shared: &Shared, - message: &Received, - receive_started: Instant, - lease_deadline: Instant, -) -> Result<(), storage_queue::Error> { - if exhausted(shared, message) { - dead_letter(shared, message, lease_deadline).await - } else { - extend( - shared, - message, - shared.config.retry.delay(message.receive_count), - receive_started, - ) - .await - } -} - -fn exhausted(shared: &Shared, message: &Received) -> bool { - shared - .config - .retry - .max_attempts - .is_some_and(|max| message.receive_count >= max) -} - -async fn dead_letter( - shared: &Shared, - message: &Received, - lease_deadline: Instant, -) -> Result<(), storage_queue::Error> { - let Some(destination) = &shared.dead_letter else { - return Err(storage_queue::Error::InvalidArgument( - "dead-letter queue is not configured", - )); - }; - let copy = Outgoing { - body: message.body.clone(), - group_id: message.group_id.clone(), - attributes: message.attributes.clone(), - }; - time::timeout_at(lease_deadline, destination.send(&[copy])) - .await - .map_err(|_| storage_queue::Error::StaleReceipt)??; - if Instant::now() >= lease_deadline { - return Err(storage_queue::Error::StaleReceipt); - } - shared.transport.delete(&[&message.receipt]).await -} - -async fn extend( - shared: &Shared, - message: &Received, - delay: Duration, - receive_started: Instant, -) -> Result<(), storage_queue::Error> { - let secs = delay - .as_secs() - .saturating_add(u64::from(delay.subsec_nanos() > 0)); - let remaining = remaining_window(receive_started, Instant::now()).min(MAX_RETRY_DELAY); - let delay = if secs > remaining.as_secs() { - warn!( - requested_seconds = secs, - remaining_seconds = remaining.as_secs(), - "retry delay shortened to the supported visibility window" - ); - remaining - } else { - Duration::from_secs(secs) - }; - shared.transport.extend(&message.receipt, delay).await -} - -fn remaining_window(receive_started: Instant, now: Instant) -> Duration { - let remaining = - (receive_started + MAX_VISIBILITY - VISIBILITY_MARGIN).saturating_duration_since(now); - Duration::from_secs(remaining.as_secs()) -} diff --git a/rust/crates/queue-transport/Cargo.toml b/rust/crates/queue-transport/Cargo.toml new file mode 100644 index 000000000..2fce70507 --- /dev/null +++ b/rust/crates/queue-transport/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "storage-queue-transport" +version = "0.1.0" +edition = "2024" + +[lib] +name = "storage_queue_transport" + +[dependencies] +aws-sdk-sqs.workspace = true +thiserror.workspace = true +tokio.workspace = true diff --git a/rust/crates/queue-transport/src/lib.rs b/rust/crates/queue-transport/src/lib.rs new file mode 100644 index 000000000..43da26524 --- /dev/null +++ b/rust/crates/queue-transport/src/lib.rs @@ -0,0 +1,142 @@ +use std::{collections::HashMap, time::Duration}; + +pub mod sqs; + +const MAX_RECEIVE: usize = 10; +const MAX_WAIT_SECS: u64 = 20; +const MAX_VISIBILITY_SECS: u64 = 12 * 60 * 60; + +/// A transport message attribute. SQS string and number values use `Text`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MessageAttribute { + pub data_type: String, + pub value: AttributeValue, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AttributeValue { + Text(String), + Binary(Vec), +} + +#[derive(Debug, Clone)] +pub struct Outgoing { + pub body: String, + pub group_id: Option, + pub attributes: HashMap, +} + +#[derive(Debug, Clone)] +pub struct Received { + pub receipt: String, + pub body: String, + pub receive_count: u32, + pub group_id: Option, + pub attributes: HashMap, +} + +pub trait Transport { + /// Enqueue, chunking as needed. Batch errors report an outcome for each input. + /// Unknown outcomes may have succeeded; retrying them can produce duplicates. + /// The underlying client may also retry requests, so a failed entry in the final + /// response does not rule out success in an earlier attempt. + fn send(&self, messages: &[Outgoing]) -> impl Future> + Send; + /// Claim up to `max` messages (1..=10), long-polling up to `wait` (<= 20 s). Claimed messages are + /// invisible for `visibility` (0 s ..= 12 h) and have receive_count incremented. + /// Durations must be whole seconds. If any returned message is malformed, the + /// whole receive fails; claimed messages remain invisible until their timeout. + /// SQS limits visibility to 12 hours from receiving the original receive request. + fn receive( + &self, + max: usize, + wait: Duration, + visibility: Duration, + ) -> impl Future, Error>> + Send; + /// Set the message's visibility timeout to `visibility` measured from now (0 = make visible now, i.e. nack). + /// Returns Error::StaleReceipt when the backend identifies the message as no longer in flight. + /// Invalid handles and other provider errors are returned separately; a provider may not + /// distinguish every stale handle from an invalid one. + /// The duration must be whole seconds and at most 12 hours. SQS also rejects a duration + /// beyond the time remaining in the 12-hour window from the original receive request; + /// the remaining window is determined by SQS, not this client. Such errors are returned + /// as Error::VisibilityChange with the provider details; the timeout is not clamped. + fn extend( + &self, + receipt: &str, + visibility: Duration, + ) -> impl Future> + Send; + /// Delete (ack). SQS may report success for an old receipt without deleting the message; + /// rejected receipts are reported as failures. + /// Batch errors report an outcome for each input. + fn delete(&self, receipts: &[&str]) -> impl Future> + Send; +} + +/// The outcome of one input in a failed batch operation. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum BatchOutcome { + Succeeded, + /// The final response rejected this entry. Earlier request attempts may have succeeded. + Failed { + code: String, + message: Option, + sender_fault: bool, + }, + /// The request may have been sent, but its result could not be determined. + Unknown, + /// No request containing this input was made. + NotAttempted, +} + +#[derive(Debug, thiserror::Error)] +#[error("{operation} batch failed")] +pub struct BatchError { + pub operation: &'static str, + /// Outcomes are ordered to match the original input slice. + pub outcomes: Vec, + #[source] + pub source: Option>, +} + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("invalid argument: {0}")] + InvalidArgument(&'static str), + #[error("stale receipt")] + StaleReceipt, + #[error("invalid SQS response: {0}")] + InvalidResponse(&'static str), + #[error("visibility change failed (code: {code:?}, message: {message:?})")] + VisibilityChange { + code: Option, + message: Option, + #[source] + source: Box, + }, + #[error(transparent)] + Batch(#[from] BatchError), + #[error(transparent)] + Sqs(Box), +} + +pub(crate) fn check_receive(max: usize, wait: Duration, visibility: Duration) -> Result<(), Error> { + if !(1..=MAX_RECEIVE).contains(&max) { + return Err(Error::InvalidArgument("max must be 1..=10")); + } + if wait.subsec_nanos() != 0 { + return Err(Error::InvalidArgument("wait must be whole seconds")); + } + if wait.as_secs() > MAX_WAIT_SECS { + return Err(Error::InvalidArgument("wait exceeds 20 seconds")); + } + check_visibility(visibility) +} + +pub(crate) fn check_visibility(visibility: Duration) -> Result<(), Error> { + if visibility.subsec_nanos() != 0 { + return Err(Error::InvalidArgument("visibility must be whole seconds")); + } + if visibility.as_secs() > MAX_VISIBILITY_SECS { + return Err(Error::InvalidArgument("visibility exceeds 12 hours")); + } + Ok(()) +} diff --git a/rust/crates/queue/src/sqs.rs b/rust/crates/queue-transport/src/sqs.rs similarity index 100% rename from rust/crates/queue/src/sqs.rs rename to rust/crates/queue-transport/src/sqs.rs diff --git a/rust/crates/queue/tests/contract.rs b/rust/crates/queue-transport/tests/contract.rs similarity index 99% rename from rust/crates/queue/tests/contract.rs rename to rust/crates/queue-transport/tests/contract.rs index a85a065f5..e9f76d2c3 100644 --- a/rust/crates/queue/tests/contract.rs +++ b/rust/crates/queue-transport/tests/contract.rs @@ -12,7 +12,7 @@ use aws_sdk_sqs::{ config::{BehaviorVersion, Credentials, Region}, types::QueueAttributeName, }; -use storage_queue::{ +use storage_queue_transport::{ AttributeValue, BatchOutcome, Error, MessageAttribute, Outgoing, Received, Transport, sqs::SqsQueue, }; diff --git a/rust/crates/queue/tests/failure_paths.rs b/rust/crates/queue-transport/tests/failure_paths.rs similarity index 99% rename from rust/crates/queue/tests/failure_paths.rs rename to rust/crates/queue-transport/tests/failure_paths.rs index 8f03fe795..17db669ad 100644 --- a/rust/crates/queue/tests/failure_paths.rs +++ b/rust/crates/queue-transport/tests/failure_paths.rs @@ -9,7 +9,7 @@ use aws_sdk_sqs::{ Client, config::{BehaviorVersion, Credentials, Region, retry::RetryConfig}, }; -use storage_queue::{ +use storage_queue_transport::{ AttributeValue, BatchOutcome, Error, MessageAttribute, Outgoing, Transport, sqs::SqsQueue, }; diff --git a/rust/crates/queue/Cargo.toml b/rust/crates/queue/Cargo.toml index 9a8e939da..1e1009ceb 100644 --- a/rust/crates/queue/Cargo.toml +++ b/rust/crates/queue/Cargo.toml @@ -7,6 +7,15 @@ edition = "2024" name = "storage_queue" [dependencies] -aws-sdk-sqs.workspace = true +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +storage-queue-transport = { path = "../queue-transport" } thiserror.workspace = true -tokio.workspace = true +tokio = { workspace = true, features = ["sync"] } +tokio-util.workspace = true +tracing.workspace = true + +[dev-dependencies] +aws-sdk-sqs.workspace = true +tokio = { workspace = true, features = ["test-util"] } diff --git a/rust/crates/queue/src/lib.rs b/rust/crates/queue/src/lib.rs index 43da26524..20bb46cfe 100644 --- a/rust/crates/queue/src/lib.rs +++ b/rust/crates/queue/src/lib.rs @@ -1,142 +1,765 @@ -use std::{collections::HashMap, time::Duration}; +use std::{collections::HashMap, future::Future, pin::Pin, sync::Arc, time::Duration}; -pub mod sqs; +use serde::{Serialize, de::DeserializeOwned}; +use serde_json::value::RawValue; +use sha2::{Digest, Sha256}; +use storage_queue_transport::{AttributeValue, MessageAttribute, Outgoing, Received, Transport}; +use tokio::{ + sync::Semaphore, + task::{JoinHandle, JoinSet}, + time::{self, Instant}, +}; +use tokio_util::sync::CancellationToken; +use tracing::{Instrument, error, info_span, warn}; -const MAX_RECEIVE: usize = 10; -const MAX_WAIT_SECS: u64 = 20; -const MAX_VISIBILITY_SECS: u64 = 12 * 60 * 60; +pub type BoxError = Box; +type BoxFuture = Pin + Send>>; +type Heartbeat<'a> = ( + Instant, + Duration, + Pin> + Send + 'a>>, +); -/// A transport message attribute. SQS string and number values use `Text`. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MessageAttribute { - pub data_type: String, - pub value: AttributeValue, +const SYSTEM_TENANT_REF: &str = "SYSTEM_TENANT"; +const HEADERS_ATTRIBUTE: &str = "queue.headers"; +const KEY_ATTRIBUTE: &str = "queue.key"; +const MAX_BATCH: usize = 10; +const MAX_WAIT: Duration = Duration::from_secs(20); +const MAX_VISIBILITY: Duration = Duration::from_secs(12 * 60 * 60); +// Matches the Node SQS adapter's cap on parked retries. +const MAX_RETRY_DELAY: Duration = Duration::from_secs(11 * 60 * 60); +// Leave time for the visibility request to reach SQS before its 12-hour deadline. +const VISIBILITY_MARGIN: Duration = Duration::from_secs(5); +const RECEIVE_RETRY_DELAY: Duration = Duration::from_secs(1); +const HEARTBEAT_RETRY: Duration = Duration::from_secs(1); + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("invalid config: {0}")] + InvalidConfig(&'static str), + #[error("encode failed: {0}")] + Encode(#[from] serde_json::Error), } -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum AttributeValue { - Text(String), - Binary(Vec), +pub trait Job: Send + Sync + 'static { + /// Queue name used by the Node manager's registry. + const NAME: &'static str; + /// Optional manager message type, carried in `queue.headers`. + const TYPE: Option<&'static str> = None; + type Payload: Serialize + DeserializeOwned + Send + 'static; + fn run( + &self, + ctx: Context, + payload: Self::Payload, + ) -> impl Future> + Send; +} + +pub struct Context { + pub tenant: Option, + pub receive_count: u32, + pub key: Option, + pub headers: HashMap, + /// Fires on timeout, shutdown, or when the message lease is lost. + pub cancel: CancellationToken, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Disposition { + Done, + /// Retry using the current receipt's visibility timeout. SQS cannot guarantee + /// delays beyond the remaining 12-hour receive window. + RetryAfter(Duration), +} + +fn payload_tenant(payload: &RawValue) -> Option { + let value = serde_json::from_str::(payload.get()).ok()?; + value.get("tenant")?.get("ref")?.as_str().map(str::to_owned) +} + +fn string_attribute(value: String) -> MessageAttribute { + MessageAttribute { + data_type: "String".into(), + value: AttributeValue::Text(value), + } +} + +fn group_id(key: &str) -> String { + if !key.is_empty() && key.len() <= 128 && key.bytes().all(|b| (0x21..=0x7e).contains(&b)) { + key.to_owned() + } else { + use std::fmt::Write; + let mut result = String::from("sha256:"); + for byte in Sha256::digest(key.as_bytes()) { + write!(&mut result, "{byte:02x}").expect("writing to a string cannot fail"); + } + result + } +} + +#[derive(Debug, Default)] +pub struct EncodeOptions<'a> { + /// Override the key derived from the payload's tenant reference. + pub key: Option<&'a str>, + /// Used as a fair-queue group when there is no key. Standard SQS does not deduplicate it. + pub idempotency_key: Option<&'a str>, + pub headers: HashMap, +} + +/// Encode the bare JSON body and manager attributes for this job's queue. +pub fn encode(payload: &J::Payload) -> Result { + encode_with_options::(payload, EncodeOptions::default()) +} + +pub fn encode_with_options( + payload: &J::Payload, + options: EncodeOptions<'_>, +) -> Result { + let payload = serde_json::value::to_raw_value(payload)?; + let tenant = payload_tenant(&payload).filter(|t| t != SYSTEM_TENANT_REF); + let key = options + .key + .or(tenant.as_deref()) + .filter(|key| !key.is_empty()); + let fair_group = key.or(options.idempotency_key.filter(|key| !key.is_empty())); + let mut attributes = HashMap::new(); + if let Some(key) = key { + attributes.insert(KEY_ATTRIBUTE.into(), string_attribute(key.to_owned())); + } + let mut headers = options.headers; + if let Some(kind) = J::TYPE { + headers + .entry("message-type".into()) + .or_insert_with(|| kind.to_owned()); + } + if !headers.is_empty() { + attributes.insert( + HEADERS_ATTRIBUTE.into(), + string_attribute(serde_json::to_string(&headers)?), + ); + } + Ok(Outgoing { + body: payload.get().to_owned(), + group_id: fair_group.map(group_id), + attributes, + }) } #[derive(Debug, Clone)] -pub struct Outgoing { - pub body: String, - pub group_id: Option, - pub attributes: HashMap, +pub struct WorkerConfig { + pub concurrency: usize, + pub batch: usize, + pub wait: Duration, + pub visibility: Duration, + /// Renew visibility while a job runs. Requires an execution timeout. + pub auto_heartbeat: bool, + /// Optional maximum handler runtime before cancellation. + pub execution_timeout: Option, + /// Failure retry policy for this queue. A limit requires a dead-letter transport. + pub retry: RetryPolicy, + /// How long a cancelled job may run before it is aborted. + pub shutdown_grace: Duration, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Backoff { + Fixed, + Exponential, } #[derive(Debug, Clone)] -pub struct Received { - pub receipt: String, - pub body: String, - pub receive_count: u32, - pub group_id: Option, - pub attributes: HashMap, -} - -pub trait Transport { - /// Enqueue, chunking as needed. Batch errors report an outcome for each input. - /// Unknown outcomes may have succeeded; retrying them can produce duplicates. - /// The underlying client may also retry requests, so a failed entry in the final - /// response does not rule out success in an earlier attempt. - fn send(&self, messages: &[Outgoing]) -> impl Future> + Send; - /// Claim up to `max` messages (1..=10), long-polling up to `wait` (<= 20 s). Claimed messages are - /// invisible for `visibility` (0 s ..= 12 h) and have receive_count incremented. - /// Durations must be whole seconds. If any returned message is malformed, the - /// whole receive fails; claimed messages remain invisible until their timeout. - /// SQS limits visibility to 12 hours from receiving the original receive request. - fn receive( +pub struct RetryPolicy { + /// Maximum deliveries, including crash redeliveries. `None` means no local limit. + pub max_attempts: Option, + pub backoff: Backoff, + pub base: Duration, + pub max: Option, +} + +impl Default for RetryPolicy { + fn default() -> Self { + Self { + max_attempts: None, + backoff: Backoff::Exponential, + base: Duration::from_secs(5), + max: Some(Duration::from_secs(300)), + } + } +} + +impl RetryPolicy { + fn delay(&self, receive_count: u32) -> Duration { + let delay = match self.backoff { + Backoff::Fixed => self.base, + Backoff::Exponential => { + let mut delay = self.base; + if !delay.is_zero() { + for _ in 0..receive_count.saturating_sub(1) { + delay = delay.saturating_mul(2); + // The SQS settle path cannot park longer than this. + if delay >= MAX_RETRY_DELAY { + break; + } + } + } + delay + } + }; + self.max.map_or(delay, |max| delay.min(max)) + } +} + +impl Default for WorkerConfig { + fn default() -> Self { + Self { + concurrency: 16, + batch: MAX_BATCH, + wait: MAX_WAIT, + visibility: Duration::from_secs(60), + auto_heartbeat: false, + execution_timeout: None, + retry: RetryPolicy::default(), + shutdown_grace: Duration::from_secs(30), + } + } +} + +impl WorkerConfig { + fn validate(&self) -> Result<(), Error> { + if !(1..=Semaphore::MAX_PERMITS).contains(&self.concurrency) { + return Err(Error::InvalidConfig( + "concurrency must be 1..=Semaphore::MAX_PERMITS", + )); + } + if !(1..=MAX_BATCH).contains(&self.batch) { + return Err(Error::InvalidConfig("batch must be 1..=10")); + } + if self.wait.subsec_nanos() != 0 || self.wait.is_zero() || self.wait > MAX_WAIT { + return Err(Error::InvalidConfig( + "wait must be whole seconds in 1..=20 s", + )); + } + if self.visibility.subsec_nanos() != 0 + || self.visibility < Duration::from_secs(2) + || self.visibility > MAX_VISIBILITY + { + return Err(Error::InvalidConfig( + "visibility must be whole seconds in 2 s..=12 h", + )); + } + if self.execution_timeout.is_some_and(|timeout| { + timeout.is_zero() || Instant::now().checked_add(timeout).is_none() + }) { + return Err(Error::InvalidConfig( + "execution_timeout must be greater than zero and representable", + )); + } + if self.auto_heartbeat && self.execution_timeout.is_none() { + return Err(Error::InvalidConfig( + "auto_heartbeat requires execution_timeout", + )); + } + if Instant::now().checked_add(self.shutdown_grace).is_none() { + return Err(Error::InvalidConfig("shutdown_grace must be representable")); + } + if self.retry.max_attempts == Some(0) { + return Err(Error::InvalidConfig("max_attempts must be at least 1")); + } + if self.retry.max.is_some_and(|max| max < self.retry.base) { + return Err(Error::InvalidConfig( + "maximum backoff must be at least the base", + )); + } + Ok(()) + } +} + +trait Handler: Send + Sync { + fn start( &self, - max: usize, - wait: Duration, - visibility: Duration, - ) -> impl Future, Error>> + Send; - /// Set the message's visibility timeout to `visibility` measured from now (0 = make visible now, i.e. nack). - /// Returns Error::StaleReceipt when the backend identifies the message as no longer in flight. - /// Invalid handles and other provider errors are returned separately; a provider may not - /// distinguish every stale handle from an invalid one. - /// The duration must be whole seconds and at most 12 hours. SQS also rejects a duration - /// beyond the time remaining in the 12-hour window from the original receive request; - /// the remaining window is determined by SQS, not this client. Such errors are returned - /// as Error::VisibilityChange with the provider details; the timeout is not clamped. - fn extend( + ctx: Context, + payload: &RawValue, + ) -> Result>, serde_json::Error>; +} + +struct Typed(Arc); + +impl Handler for Typed { + fn start( &self, - receipt: &str, - visibility: Duration, - ) -> impl Future> + Send; - /// Delete (ack). SQS may report success for an old receipt without deleting the message; - /// rejected receipts are reported as failures. - /// Batch errors report an outcome for each input. - fn delete(&self, receipts: &[&str]) -> impl Future> + Send; -} - -/// The outcome of one input in a failed batch operation. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum BatchOutcome { - Succeeded, - /// The final response rejected this entry. Earlier request attempts may have succeeded. - Failed { - code: String, - message: Option, - sender_fault: bool, - }, - /// The request may have been sent, but its result could not be determined. - Unknown, - /// No request containing this input was made. - NotAttempted, + ctx: Context, + payload: &RawValue, + ) -> Result>, serde_json::Error> { + let payload = serde_json::from_str(payload.get())?; + let job = self.0.clone(); + Ok(Box::pin(async move { job.run(ctx, payload).await })) + } } -#[derive(Debug, thiserror::Error)] -#[error("{operation} batch failed")] -pub struct BatchError { - pub operation: &'static str, - /// Outcomes are ordered to match the original input slice. - pub outcomes: Vec, - #[source] - pub source: Option>, +struct AbortOnDrop(JoinHandle); + +impl Drop for AbortOnDrop { + fn drop(&mut self) { + self.0.abort(); + } } -#[derive(Debug, thiserror::Error)] -pub enum Error { - #[error("invalid argument: {0}")] - InvalidArgument(&'static str), - #[error("stale receipt")] - StaleReceipt, - #[error("invalid SQS response: {0}")] - InvalidResponse(&'static str), - #[error("visibility change failed (code: {code:?}, message: {message:?})")] - VisibilityChange { - code: Option, - message: Option, - #[source] - source: Box, - }, - #[error(transparent)] - Batch(#[from] BatchError), - #[error(transparent)] - Sqs(Box), -} - -pub(crate) fn check_receive(max: usize, wait: Duration, visibility: Duration) -> Result<(), Error> { - if !(1..=MAX_RECEIVE).contains(&max) { - return Err(Error::InvalidArgument("max must be 1..=10")); - } - if wait.subsec_nanos() != 0 { - return Err(Error::InvalidArgument("wait must be whole seconds")); - } - if wait.as_secs() > MAX_WAIT_SECS { - return Err(Error::InvalidArgument("wait exceeds 20 seconds")); - } - check_visibility(visibility) -} - -pub(crate) fn check_visibility(visibility: Duration) -> Result<(), Error> { - if visibility.subsec_nanos() != 0 { - return Err(Error::InvalidArgument("visibility must be whole seconds")); - } - if visibility.as_secs() > MAX_VISIBILITY_SECS { - return Err(Error::InvalidArgument("visibility exceeds 12 hours")); - } - Ok(()) +struct Shared { + transport: Arc, + config: WorkerConfig, + handler: Box, + queue: &'static str, + dead_letter: Option>, + jobs: CancellationToken, +} + +pub struct Worker { + transport: Arc, + config: WorkerConfig, + handler: Option<(&'static str, Box)>, + dead_letter: Option>, +} + +impl Worker { + pub fn new(transport: Arc, config: WorkerConfig) -> Result { + config.validate()?; + Ok(Self { + transport, + config, + handler: None, + dead_letter: None, + }) + } + + /// Bind the single job handled by this queue. Panics if already bound. + pub fn register(&mut self, job: J) { + assert!(self.handler.is_none(), "a job is already registered"); + self.handler = Some((J::NAME, Box::new(Typed(Arc::new(job))))); + } + + /// Supply a distinct queue for exhausted messages. Delivery to it is at least once. + pub fn set_dead_letter(&mut self, transport: Arc) { + self.dead_letter = Some(transport); + } + + pub async fn run(self, shutdown: CancellationToken) -> Result<(), Error> { + let (queue, handler) = self + .handler + .ok_or(Error::InvalidConfig("no job registered"))?; + if self.config.retry.max_attempts.is_some() && self.dead_letter.is_none() { + return Err(Error::InvalidConfig( + "max_attempts requires a dead-letter queue", + )); + } + if self + .dead_letter + .as_ref() + .is_some_and(|dlq| Arc::ptr_eq(dlq, &self.transport)) + { + return Err(Error::InvalidConfig( + "dead-letter queue must be distinct from the source", + )); + } + let grace = self.config.shutdown_grace; + let shared = Arc::new(Shared { + transport: self.transport, + config: self.config, + handler, + queue, + dead_letter: self.dead_letter, + jobs: CancellationToken::new(), + }); + let permits = Arc::new(Semaphore::new(shared.config.concurrency)); + let mut tasks = JoinSet::new(); + + while let Some(messages) = receive(&shared, &permits, &shutdown).await { + for (message, permit, received_at, receive_started) in messages { + let shared = shared.clone(); + tasks.spawn(async move { + handle(&shared, message, received_at, receive_started).await; + drop(permit); + }); + } + while tasks.try_join_next().is_some() {} + } + + shared.jobs.cancel(); + let drain = async { while tasks.join_next().await.is_some() {} }; + if time::timeout(grace, drain).await.is_err() { + warn!("shutdown grace elapsed, aborting in-flight jobs"); + } + tasks.shutdown().await; + Ok(()) + } +} + +async fn receive( + shared: &Shared, + permits: &Arc, + shutdown: &CancellationToken, +) -> Option< + Vec<( + Received, + tokio::sync::OwnedSemaphorePermit, + Instant, + Instant, + )>, +> { + let config = &shared.config; + let first = tokio::select! { + biased; + _ = shutdown.cancelled() => return None, + permit = permits.clone().acquire_owned() => permit.expect("semaphore is never closed"), + }; + let mut held = vec![first]; + while held.len() < config.batch { + match permits.clone().try_acquire_owned() { + Ok(permit) => held.push(permit), + Err(_) => break, + } + } + let receive_started = Instant::now(); + let result = tokio::select! { + biased; + _ = shutdown.cancelled() => return None, + result = shared.transport.receive(held.len(), config.wait, config.visibility) => result, + }; + match result { + Ok(messages) => { + let received_at = Instant::now(); + Some( + messages + .into_iter() + .zip(held) + .map(|(message, permit)| (message, permit, received_at, receive_started)) + .collect(), + ) + } + Err(e) => { + warn!(error = ?e, "receive failed"); + tokio::select! { + _ = shutdown.cancelled() => None, + _ = time::sleep(RECEIVE_RETRY_DELAY) => Some(Vec::new()), + } + } + } +} + +async fn handle( + shared: &Shared, + message: Received, + received_at: Instant, + receive_started: Instant, +) { + let deadline = received_at + shared.config.visibility; + if shared + .config + .retry + .max_attempts + .is_some_and(|max| message.receive_count > max) + { + if let Err(e) = dead_letter(shared, &message, deadline).await { + warn!(error = ?e, "dead-lettering failed; original message remains in the queue"); + } + return; + } + let payload = match serde_json::from_str::>(&message.body) { + Ok(payload) => payload, + Err(e) => { + warn!(error = %e, receive_count = message.receive_count, "invalid JSON payload"); + if let Err(e) = retry_later(shared, &message, receive_started, deadline).await { + warn!(error = ?e, "disposition failed"); + } + return; + } + }; + let tenant = payload_tenant(&payload); + let span = info_span!( + "job", + name = %shared.queue, + tenant = ?tenant, + receive_count = message.receive_count + ); + process( + shared, + message, + payload, + tenant, + received_at, + receive_started, + ) + .instrument(span) + .await; +} + +fn text_attribute<'a>(message: &'a Received, name: &str) -> Option<&'a str> { + match &message.attributes.get(name)?.value { + AttributeValue::Text(text) => Some(text), + AttributeValue::Binary(_) => None, + } +} + +fn message_headers(message: &Received) -> HashMap { + if let Some(packed) = text_attribute(message, HEADERS_ATTRIBUTE) { + return match serde_json::from_str::(packed) { + Ok(serde_json::Value::Object(headers)) => headers + .into_iter() + .filter_map(|(name, value)| value.as_str().map(|text| (name, text.to_owned()))) + .collect(), + _ => HashMap::new(), + }; + } + message + .attributes + .iter() + .filter_map(|(name, attribute)| { + if name.starts_with("queue.") || attribute.data_type.starts_with("Binary") { + return None; + } + match &attribute.value { + AttributeValue::Text(value) => Some((name.clone(), value.clone())), + AttributeValue::Binary(_) => None, + } + }) + .collect() +} + +async fn process( + shared: &Shared, + message: Received, + payload: Box, + tenant: Option, + received_at: Instant, + receive_started: Instant, +) { + let cancel = shared.jobs.child_token(); + let ctx = Context { + tenant, + receive_count: message.receive_count, + key: text_attribute(&message, KEY_ATTRIBUTE).map(str::to_owned), + headers: message_headers(&message), + cancel: cancel.clone(), + }; + let future = match shared.handler.start(ctx, &payload) { + Ok(future) => future, + Err(e) => { + warn!(error = %e, "invalid payload"); + if let Err(e) = retry_later( + shared, + &message, + receive_started, + received_at + shared.config.visibility, + ) + .await + { + warn!(error = ?e, "disposition failed"); + } + return; + } + }; + let execution_deadline = shared + .config + .execution_timeout + .map(|timeout| Instant::now() + timeout); + let mut job = AbortOnDrop(tokio::spawn(future.in_current_span())); + + let visibility = shared.config.visibility; + let half = visibility / 2; + let mut next_beat = received_at + half; + let mut heartbeat: Option> = None; + let mut lease_deadline = received_at + visibility; + let mut cancel_deadline = None; + let mut timed_out = false; + // Lease-loss branches precede the job so that a ready loss is never ignored. + let joined = loop { + tokio::select! { + biased; + _ = time::sleep_until(lease_deadline) => { + warn!("visibility expired, cancelling job"); + break None; + } + result = async { heartbeat.as_mut().expect("guarded").2.as_mut().await }, if heartbeat.is_some() => { + let (started, duration, _) = heartbeat.take().expect("guarded"); + match result { + Ok(()) => { + lease_deadline = started + duration; + next_beat = started + half; + } + Err(storage_queue_transport::Error::StaleReceipt) => { + warn!("lease lost, cancelling job"); + break None; + } + Err(e) => { + warn!(error = ?e, "heartbeat failed"); + next_beat = Instant::now() + HEARTBEAT_RETRY.min(half); + } + } + } + joined = &mut job.0 => break Some(joined), + _ = async { time::sleep_until(execution_deadline.expect("guarded")).await }, if execution_deadline.is_some() && cancel_deadline.is_none() => { + warn!("job execution timed out, cancelling job"); + cancel.cancel(); + cancel_deadline = Some(Instant::now() + shared.config.shutdown_grace); + } + _ = async { time::sleep_until(cancel_deadline.expect("guarded")).await }, if cancel_deadline.is_some() => { + warn!("job ignored cancellation, aborting"); + job.0.abort(); + let joined = (&mut job.0).await; + timed_out = matches!(&joined, Err(e) if e.is_cancelled()); + break Some(joined); + } + _ = time::sleep_until(next_beat), if shared.config.auto_heartbeat && heartbeat.is_none() => { + let started = Instant::now(); + let duration = visibility.min(remaining_window(receive_started, started)); + if duration.is_zero() { + warn!("visibility window exhausted, cancelling job"); + break None; + } + heartbeat = Some(( + started, + duration, + Box::pin(shared.transport.extend(&message.receipt, duration)), + )); + } + } + }; + let Some(joined) = joined else { + // A lost lease must not settle a delivery that may now be owned elsewhere. + cancel.cancel(); + if time::timeout(shared.config.shutdown_grace, &mut job.0) + .await + .is_err() + { + warn!("job ignored cancellation, aborting"); + } + return; + }; + + if !matches!(joined, Ok(Ok(Disposition::Done))) { + // A late heartbeat would override the retry delay. + if let Some((started, duration, extend)) = heartbeat { + match time::timeout_at(lease_deadline, extend).await { + Ok(Ok(())) => lease_deadline = started + duration, + Ok(Err(storage_queue_transport::Error::StaleReceipt)) => return, + Ok(Err(_)) | Err(_) => {} + } + } + } + if Instant::now() >= lease_deadline { + return; + } + let result = if timed_out { + if shared.jobs.is_cancelled() { + extend(shared, &message, Duration::ZERO, receive_started).await + } else { + retry_later(shared, &message, receive_started, lease_deadline).await + } + } else { + match joined { + Ok(Ok(Disposition::Done)) => shared.transport.delete(&[&message.receipt]).await, + Ok(Ok(Disposition::RetryAfter(delay))) => { + if shared.jobs.is_cancelled() { + extend(shared, &message, Duration::ZERO, receive_started).await + } else if exhausted(shared, &message) { + dead_letter(shared, &message, lease_deadline).await + } else { + extend(shared, &message, delay, receive_started).await + } + } + Ok(Err(e)) => { + error!(error = %e, "job failed"); + if shared.jobs.is_cancelled() { + extend(shared, &message, Duration::ZERO, receive_started).await + } else { + retry_later(shared, &message, receive_started, lease_deadline).await + } + } + Err(e) => { + error!(error = %e, "job panicked"); + retry_later(shared, &message, receive_started, lease_deadline).await + } + } + }; + if let Err(e) = result { + warn!(error = ?e, "disposition failed, message will reappear after visibility timeout"); + } +} + +async fn retry_later( + shared: &Shared, + message: &Received, + receive_started: Instant, + lease_deadline: Instant, +) -> Result<(), storage_queue_transport::Error> { + if exhausted(shared, message) { + dead_letter(shared, message, lease_deadline).await + } else { + extend( + shared, + message, + shared.config.retry.delay(message.receive_count), + receive_started, + ) + .await + } +} + +fn exhausted(shared: &Shared, message: &Received) -> bool { + shared + .config + .retry + .max_attempts + .is_some_and(|max| message.receive_count >= max) +} + +async fn dead_letter( + shared: &Shared, + message: &Received, + lease_deadline: Instant, +) -> Result<(), storage_queue_transport::Error> { + let Some(destination) = &shared.dead_letter else { + return Err(storage_queue_transport::Error::InvalidArgument( + "dead-letter queue is not configured", + )); + }; + let copy = Outgoing { + body: message.body.clone(), + group_id: message.group_id.clone(), + attributes: message.attributes.clone(), + }; + time::timeout_at(lease_deadline, destination.send(&[copy])) + .await + .map_err(|_| storage_queue_transport::Error::StaleReceipt)??; + if Instant::now() >= lease_deadline { + return Err(storage_queue_transport::Error::StaleReceipt); + } + shared.transport.delete(&[&message.receipt]).await +} + +async fn extend( + shared: &Shared, + message: &Received, + delay: Duration, + receive_started: Instant, +) -> Result<(), storage_queue_transport::Error> { + let secs = delay + .as_secs() + .saturating_add(u64::from(delay.subsec_nanos() > 0)); + let remaining = remaining_window(receive_started, Instant::now()).min(MAX_RETRY_DELAY); + let delay = if secs > remaining.as_secs() { + warn!( + requested_seconds = secs, + remaining_seconds = remaining.as_secs(), + "retry delay shortened to the supported visibility window" + ); + remaining + } else { + Duration::from_secs(secs) + }; + shared.transport.extend(&message.receipt, delay).await +} + +fn remaining_window(receive_started: Instant, now: Instant) -> Duration { + let remaining = + (receive_started + MAX_VISIBILITY - VISIBILITY_MARGIN).saturating_duration_since(now); + Duration::from_secs(remaining.as_secs()) } diff --git a/rust/crates/jobs/tests/fixtures/node-payload.json b/rust/crates/queue/tests/fixtures/node-payload.json similarity index 100% rename from rust/crates/jobs/tests/fixtures/node-payload.json rename to rust/crates/queue/tests/fixtures/node-payload.json diff --git a/rust/crates/jobs/tests/sqs.rs b/rust/crates/queue/tests/sqs.rs similarity index 98% rename from rust/crates/jobs/tests/sqs.rs rename to rust/crates/queue/tests/sqs.rs index e7429b457..aa73aae04 100644 --- a/rust/crates/jobs/tests/sqs.rs +++ b/rust/crates/queue/tests/sqs.rs @@ -11,10 +11,10 @@ use aws_sdk_sqs::{ config::{BehaviorVersion, Credentials, Region}, }; use serde::{Deserialize, Serialize}; -use storage_jobs::{ +use storage_queue::{ BoxError, Context, Disposition, Job, RetryPolicy, Worker, WorkerConfig, encode, }; -use storage_queue::{Transport, sqs::SqsQueue}; +use storage_queue_transport::{Transport, sqs::SqsQueue}; use tokio::time::{Instant, sleep}; use tokio_util::sync::CancellationToken; diff --git a/rust/crates/jobs/tests/worker.rs b/rust/crates/queue/tests/worker.rs similarity index 98% rename from rust/crates/jobs/tests/worker.rs rename to rust/crates/queue/tests/worker.rs index 21f9d9006..63720b1e6 100644 --- a/rust/crates/jobs/tests/worker.rs +++ b/rust/crates/queue/tests/worker.rs @@ -7,11 +7,11 @@ use std::{ }; use serde::{Deserialize, Serialize}; -use storage_jobs::{ +use storage_queue::{ Backoff, BoxError, Context, Disposition, EncodeOptions, Error, Job, RetryPolicy, Worker, WorkerConfig, encode, encode_with_options, }; -use storage_queue::{AttributeValue, MessageAttribute, Outgoing, Received, Transport}; +use storage_queue_transport::{AttributeValue, MessageAttribute, Outgoing, Received, Transport}; use tokio::{ sync::{Notify, Semaphore}, task::JoinHandle, @@ -208,10 +208,10 @@ impl Fake { } impl Transport for Fake { - async fn send(&self, messages: &[Outgoing]) -> Result<(), storage_queue::Error> { + async fn send(&self, messages: &[Outgoing]) -> Result<(), storage_queue_transport::Error> { self.calls.lock().unwrap().push(Call::Send); if self.fail_sends.load(SeqCst) { - return Err(storage_queue::Error::InvalidResponse( + return Err(storage_queue_transport::Error::InvalidResponse( "injected send failure", )); } @@ -230,7 +230,7 @@ impl Transport for Fake { max: usize, wait: Duration, visibility: Duration, - ) -> Result, storage_queue::Error> { + ) -> Result, storage_queue_transport::Error> { self.calls.lock().unwrap().push(Call::Receive { max, running: self.stats.running.load(SeqCst), @@ -240,7 +240,7 @@ impl Transport for Fake { .try_update(SeqCst, SeqCst, |n| n.checked_sub(1)) .is_ok() { - return Err(storage_queue::Error::InvalidResponse("injected")); + return Err(storage_queue_transport::Error::InvalidResponse("injected")); } let deadline = Instant::now() + wait; loop { @@ -275,7 +275,7 @@ impl Transport for Fake { &self, receipt: &str, visibility: Duration, - ) -> Result<(), storage_queue::Error> { + ) -> Result<(), storage_queue_transport::Error> { assert!( visibility.subsec_nanos() == 0 && visibility <= Duration::from_secs(12 * 3600), "invalid visibility {visibility:?}" @@ -300,12 +300,12 @@ impl Transport for Fake { .try_update(SeqCst, SeqCst, |n| n.checked_sub(1)) .is_ok() { - return Err(storage_queue::Error::InvalidResponse( + return Err(storage_queue_transport::Error::InvalidResponse( "injected heartbeat failure", )); } if *self.stale.lock().unwrap() { - return Err(storage_queue::Error::StaleReceipt); + return Err(storage_queue_transport::Error::StaleReceipt); } if let Some(m) = self .msgs @@ -319,7 +319,7 @@ impl Transport for Fake { Ok(()) } - async fn delete(&self, receipts: &[&str]) -> Result<(), storage_queue::Error> { + async fn delete(&self, receipts: &[&str]) -> Result<(), storage_queue_transport::Error> { for r in receipts { self.calls.lock().unwrap().push(Call::Delete((*r).into())); self.msgs.lock().unwrap().retain(|m| m.receipt != *r); diff --git a/src/internal/queue/event.test.ts b/src/internal/queue/event.test.ts index 20e2a3f7e..e5a4d575e 100644 --- a/src/internal/queue/event.test.ts +++ b/src/internal/queue/event.test.ts @@ -69,7 +69,7 @@ describe('Event payload versioning', () => { const fixture = JSON.parse( readFileSync( - join(__dirname, '../../../rust/crates/jobs/tests/fixtures/node-payload.json'), + join(__dirname, '../../../rust/crates/queue/tests/fixtures/node-payload.json'), 'utf8' ) ) From 57e0bb176dcde06575b397999d855663aaa2e8c4 Mon Sep 17 00:00:00 2001 From: Ferhat Elmas Date: Fri, 13 Nov 2026 09:23:02 +0100 Subject: [PATCH 3/4] refactor: split Signed-off-by: Ferhat Elmas --- .github/workflows/rust.yml | 2 +- rust/README.md | 2 +- rust/crates/queue-transport/tests/contract.rs | 12 +- rust/crates/queue/src/config.rs | 140 ++++ rust/crates/queue/src/job.rs | 44 + rust/crates/queue/src/lib.rs | 774 +----------------- rust/crates/queue/src/message.rs | 116 +++ rust/crates/queue/src/worker.rs | 191 +++++ rust/crates/queue/src/worker/process.rs | 230 ++++++ rust/crates/queue/src/worker/settlement.rs | 91 ++ rust/crates/queue/tests/sqs.rs | 5 +- 11 files changed, 830 insertions(+), 777 deletions(-) create mode 100644 rust/crates/queue/src/config.rs create mode 100644 rust/crates/queue/src/job.rs create mode 100644 rust/crates/queue/src/message.rs create mode 100644 rust/crates/queue/src/worker.rs create mode 100644 rust/crates/queue/src/worker/process.rs create mode 100644 rust/crates/queue/src/worker/settlement.rs diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 89a3d664a..e7e113f23 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -53,4 +53,4 @@ jobs: - name: Test SQS run: cargo test --locked -- --ignored env: - STORAGE_QUEUE_TEST_SQS_ENDPOINT: http://127.0.0.1:9324 + QUEUE_TEST_SQS_ENDPOINT: http://127.0.0.1:9324 diff --git a/rust/README.md b/rust/README.md index d046ff9ab..63aa9974d 100644 --- a/rust/README.md +++ b/rust/README.md @@ -29,5 +29,5 @@ The SQS tests require an endpoint and are ignored by default. Start ElasticMQ fr Then run from `rust/`: - STORAGE_QUEUE_TEST_SQS_ENDPOINT=http://127.0.0.1:9324 \ + QUEUE_TEST_SQS_ENDPOINT=http://127.0.0.1:9324 \ cargo test -- --ignored diff --git a/rust/crates/queue-transport/tests/contract.rs b/rust/crates/queue-transport/tests/contract.rs index e9f76d2c3..d1a0468c6 100644 --- a/rust/crates/queue-transport/tests/contract.rs +++ b/rust/crates/queue-transport/tests/contract.rs @@ -18,7 +18,7 @@ use storage_queue_transport::{ }; use tokio::time::sleep; -const SQS_ENDPOINT: &str = "STORAGE_QUEUE_TEST_SQS_ENDPOINT"; +const SQS_ENDPOINT: &str = "QUEUE_TEST_SQS_ENDPOINT"; static COUNTER: AtomicUsize = AtomicUsize::new(0); @@ -64,17 +64,15 @@ async fn create_queue(client: &Client, name: &str, redrive: Option<(&str, u32)>) } async fn sqs_queue(test: &str) -> SqsQueue { - let client = sqs_client( - &std::env::var(SQS_ENDPOINT).expect("STORAGE_QUEUE_TEST_SQS_ENDPOINT must be set"), - ); + let client = + sqs_client(&std::env::var(SQS_ENDPOINT).expect("QUEUE_TEST_SQS_ENDPOINT must be set")); let url = create_queue(&client, &unique(test), None).await; SqsQueue::new(client, url) } async fn sqs_redrive(test: &str, max_receive_count: u32) -> (SqsQueue, SqsQueue) { - let client = sqs_client( - &std::env::var(SQS_ENDPOINT).expect("STORAGE_QUEUE_TEST_SQS_ENDPOINT must be set"), - ); + let client = + sqs_client(&std::env::var(SQS_ENDPOINT).expect("QUEUE_TEST_SQS_ENDPOINT must be set")); let dlq_url = create_queue(&client, &unique(&format!("{test}-dlq")), None).await; let url = create_queue(&client, &unique(test), Some((&dlq_url, max_receive_count))).await; ( diff --git a/rust/crates/queue/src/config.rs b/rust/crates/queue/src/config.rs new file mode 100644 index 000000000..7807fe204 --- /dev/null +++ b/rust/crates/queue/src/config.rs @@ -0,0 +1,140 @@ +use std::time::Duration; + +use tokio::{sync::Semaphore, time::Instant}; + +use crate::Error; + +const MAX_BATCH: usize = 10; +const MAX_WAIT: Duration = Duration::from_secs(20); +pub(crate) const MAX_VISIBILITY: Duration = Duration::from_secs(12 * 60 * 60); +// Matches the Node SQS adapter's cap on parked retries. +pub(crate) const MAX_RETRY_DELAY: Duration = Duration::from_secs(11 * 60 * 60); + +#[derive(Debug, Clone)] +pub struct WorkerConfig { + pub concurrency: usize, + pub batch: usize, + pub wait: Duration, + pub visibility: Duration, + /// Renew visibility while a job runs. Requires an execution timeout. + pub auto_heartbeat: bool, + /// Optional maximum handler runtime before cancellation. + pub execution_timeout: Option, + /// Failure retry policy for this queue. A limit requires a dead-letter transport. + pub retry: RetryPolicy, + /// How long a cancelled job may run before it is aborted. + pub shutdown_grace: Duration, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Backoff { + Fixed, + Exponential, +} + +#[derive(Debug, Clone)] +pub struct RetryPolicy { + /// Maximum deliveries, including crash redeliveries. `None` means no local limit. + pub max_attempts: Option, + pub backoff: Backoff, + pub base: Duration, + pub max: Option, +} + +impl Default for RetryPolicy { + fn default() -> Self { + Self { + max_attempts: None, + backoff: Backoff::Exponential, + base: Duration::from_secs(5), + max: Some(Duration::from_secs(300)), + } + } +} + +impl RetryPolicy { + pub(crate) fn delay(&self, receive_count: u32) -> Duration { + let delay = match self.backoff { + Backoff::Fixed => self.base, + Backoff::Exponential => { + let mut delay = self.base; + if !delay.is_zero() { + for _ in 0..receive_count.saturating_sub(1) { + delay = delay.saturating_mul(2); + // The SQS settle path cannot park longer than this. + if delay >= MAX_RETRY_DELAY { + break; + } + } + } + delay + } + }; + self.max.map_or(delay, |max| delay.min(max)) + } +} + +impl Default for WorkerConfig { + fn default() -> Self { + Self { + concurrency: 16, + batch: MAX_BATCH, + wait: MAX_WAIT, + visibility: Duration::from_secs(60), + auto_heartbeat: false, + execution_timeout: None, + retry: RetryPolicy::default(), + shutdown_grace: Duration::from_secs(30), + } + } +} + +impl WorkerConfig { + pub(crate) fn validate(&self) -> Result<(), Error> { + if !(1..=Semaphore::MAX_PERMITS).contains(&self.concurrency) { + return Err(Error::InvalidConfig( + "concurrency must be 1..=Semaphore::MAX_PERMITS", + )); + } + if !(1..=MAX_BATCH).contains(&self.batch) { + return Err(Error::InvalidConfig("batch must be 1..=10")); + } + if self.wait.subsec_nanos() != 0 || self.wait.is_zero() || self.wait > MAX_WAIT { + return Err(Error::InvalidConfig( + "wait must be whole seconds in 1..=20 s", + )); + } + if self.visibility.subsec_nanos() != 0 + || self.visibility < Duration::from_secs(2) + || self.visibility > MAX_VISIBILITY + { + return Err(Error::InvalidConfig( + "visibility must be whole seconds in 2 s..=12 h", + )); + } + if self.execution_timeout.is_some_and(|timeout| { + timeout.is_zero() || Instant::now().checked_add(timeout).is_none() + }) { + return Err(Error::InvalidConfig( + "execution_timeout must be greater than zero and representable", + )); + } + if self.auto_heartbeat && self.execution_timeout.is_none() { + return Err(Error::InvalidConfig( + "auto_heartbeat requires execution_timeout", + )); + } + if Instant::now().checked_add(self.shutdown_grace).is_none() { + return Err(Error::InvalidConfig("shutdown_grace must be representable")); + } + if self.retry.max_attempts == Some(0) { + return Err(Error::InvalidConfig("max_attempts must be at least 1")); + } + if self.retry.max.is_some_and(|max| max < self.retry.base) { + return Err(Error::InvalidConfig( + "maximum backoff must be at least the base", + )); + } + Ok(()) + } +} diff --git a/rust/crates/queue/src/job.rs b/rust/crates/queue/src/job.rs new file mode 100644 index 000000000..7581aa0e9 --- /dev/null +++ b/rust/crates/queue/src/job.rs @@ -0,0 +1,44 @@ +use std::{collections::HashMap, future::Future, time::Duration}; + +use serde::{Serialize, de::DeserializeOwned}; +use tokio_util::sync::CancellationToken; + +pub type BoxError = Box; + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("invalid config: {0}")] + InvalidConfig(&'static str), + #[error("encode failed: {0}")] + Encode(#[from] serde_json::Error), +} + +pub trait Job: Send + Sync + 'static { + /// Queue name used by the Node manager's registry. + const NAME: &'static str; + /// Optional manager message type, carried in `queue.headers`. + const TYPE: Option<&'static str> = None; + type Payload: Serialize + DeserializeOwned + Send + 'static; + fn run( + &self, + ctx: Context, + payload: Self::Payload, + ) -> impl Future> + Send; +} + +pub struct Context { + pub tenant: Option, + pub receive_count: u32, + pub key: Option, + pub headers: HashMap, + /// Fires on timeout, shutdown, or when the message lease is lost. + pub cancel: CancellationToken, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Disposition { + Done, + /// Retry using the current receipt's visibility timeout. SQS cannot guarantee + /// delays beyond the remaining 12-hour receive window. + RetryAfter(Duration), +} diff --git a/rust/crates/queue/src/lib.rs b/rust/crates/queue/src/lib.rs index 20bb46cfe..6c51ff854 100644 --- a/rust/crates/queue/src/lib.rs +++ b/rust/crates/queue/src/lib.rs @@ -1,765 +1,9 @@ -use std::{collections::HashMap, future::Future, pin::Pin, sync::Arc, time::Duration}; - -use serde::{Serialize, de::DeserializeOwned}; -use serde_json::value::RawValue; -use sha2::{Digest, Sha256}; -use storage_queue_transport::{AttributeValue, MessageAttribute, Outgoing, Received, Transport}; -use tokio::{ - sync::Semaphore, - task::{JoinHandle, JoinSet}, - time::{self, Instant}, -}; -use tokio_util::sync::CancellationToken; -use tracing::{Instrument, error, info_span, warn}; - -pub type BoxError = Box; -type BoxFuture = Pin + Send>>; -type Heartbeat<'a> = ( - Instant, - Duration, - Pin> + Send + 'a>>, -); - -const SYSTEM_TENANT_REF: &str = "SYSTEM_TENANT"; -const HEADERS_ATTRIBUTE: &str = "queue.headers"; -const KEY_ATTRIBUTE: &str = "queue.key"; -const MAX_BATCH: usize = 10; -const MAX_WAIT: Duration = Duration::from_secs(20); -const MAX_VISIBILITY: Duration = Duration::from_secs(12 * 60 * 60); -// Matches the Node SQS adapter's cap on parked retries. -const MAX_RETRY_DELAY: Duration = Duration::from_secs(11 * 60 * 60); -// Leave time for the visibility request to reach SQS before its 12-hour deadline. -const VISIBILITY_MARGIN: Duration = Duration::from_secs(5); -const RECEIVE_RETRY_DELAY: Duration = Duration::from_secs(1); -const HEARTBEAT_RETRY: Duration = Duration::from_secs(1); - -#[derive(Debug, thiserror::Error)] -pub enum Error { - #[error("invalid config: {0}")] - InvalidConfig(&'static str), - #[error("encode failed: {0}")] - Encode(#[from] serde_json::Error), -} - -pub trait Job: Send + Sync + 'static { - /// Queue name used by the Node manager's registry. - const NAME: &'static str; - /// Optional manager message type, carried in `queue.headers`. - const TYPE: Option<&'static str> = None; - type Payload: Serialize + DeserializeOwned + Send + 'static; - fn run( - &self, - ctx: Context, - payload: Self::Payload, - ) -> impl Future> + Send; -} - -pub struct Context { - pub tenant: Option, - pub receive_count: u32, - pub key: Option, - pub headers: HashMap, - /// Fires on timeout, shutdown, or when the message lease is lost. - pub cancel: CancellationToken, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Disposition { - Done, - /// Retry using the current receipt's visibility timeout. SQS cannot guarantee - /// delays beyond the remaining 12-hour receive window. - RetryAfter(Duration), -} - -fn payload_tenant(payload: &RawValue) -> Option { - let value = serde_json::from_str::(payload.get()).ok()?; - value.get("tenant")?.get("ref")?.as_str().map(str::to_owned) -} - -fn string_attribute(value: String) -> MessageAttribute { - MessageAttribute { - data_type: "String".into(), - value: AttributeValue::Text(value), - } -} - -fn group_id(key: &str) -> String { - if !key.is_empty() && key.len() <= 128 && key.bytes().all(|b| (0x21..=0x7e).contains(&b)) { - key.to_owned() - } else { - use std::fmt::Write; - let mut result = String::from("sha256:"); - for byte in Sha256::digest(key.as_bytes()) { - write!(&mut result, "{byte:02x}").expect("writing to a string cannot fail"); - } - result - } -} - -#[derive(Debug, Default)] -pub struct EncodeOptions<'a> { - /// Override the key derived from the payload's tenant reference. - pub key: Option<&'a str>, - /// Used as a fair-queue group when there is no key. Standard SQS does not deduplicate it. - pub idempotency_key: Option<&'a str>, - pub headers: HashMap, -} - -/// Encode the bare JSON body and manager attributes for this job's queue. -pub fn encode(payload: &J::Payload) -> Result { - encode_with_options::(payload, EncodeOptions::default()) -} - -pub fn encode_with_options( - payload: &J::Payload, - options: EncodeOptions<'_>, -) -> Result { - let payload = serde_json::value::to_raw_value(payload)?; - let tenant = payload_tenant(&payload).filter(|t| t != SYSTEM_TENANT_REF); - let key = options - .key - .or(tenant.as_deref()) - .filter(|key| !key.is_empty()); - let fair_group = key.or(options.idempotency_key.filter(|key| !key.is_empty())); - let mut attributes = HashMap::new(); - if let Some(key) = key { - attributes.insert(KEY_ATTRIBUTE.into(), string_attribute(key.to_owned())); - } - let mut headers = options.headers; - if let Some(kind) = J::TYPE { - headers - .entry("message-type".into()) - .or_insert_with(|| kind.to_owned()); - } - if !headers.is_empty() { - attributes.insert( - HEADERS_ATTRIBUTE.into(), - string_attribute(serde_json::to_string(&headers)?), - ); - } - Ok(Outgoing { - body: payload.get().to_owned(), - group_id: fair_group.map(group_id), - attributes, - }) -} - -#[derive(Debug, Clone)] -pub struct WorkerConfig { - pub concurrency: usize, - pub batch: usize, - pub wait: Duration, - pub visibility: Duration, - /// Renew visibility while a job runs. Requires an execution timeout. - pub auto_heartbeat: bool, - /// Optional maximum handler runtime before cancellation. - pub execution_timeout: Option, - /// Failure retry policy for this queue. A limit requires a dead-letter transport. - pub retry: RetryPolicy, - /// How long a cancelled job may run before it is aborted. - pub shutdown_grace: Duration, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Backoff { - Fixed, - Exponential, -} - -#[derive(Debug, Clone)] -pub struct RetryPolicy { - /// Maximum deliveries, including crash redeliveries. `None` means no local limit. - pub max_attempts: Option, - pub backoff: Backoff, - pub base: Duration, - pub max: Option, -} - -impl Default for RetryPolicy { - fn default() -> Self { - Self { - max_attempts: None, - backoff: Backoff::Exponential, - base: Duration::from_secs(5), - max: Some(Duration::from_secs(300)), - } - } -} - -impl RetryPolicy { - fn delay(&self, receive_count: u32) -> Duration { - let delay = match self.backoff { - Backoff::Fixed => self.base, - Backoff::Exponential => { - let mut delay = self.base; - if !delay.is_zero() { - for _ in 0..receive_count.saturating_sub(1) { - delay = delay.saturating_mul(2); - // The SQS settle path cannot park longer than this. - if delay >= MAX_RETRY_DELAY { - break; - } - } - } - delay - } - }; - self.max.map_or(delay, |max| delay.min(max)) - } -} - -impl Default for WorkerConfig { - fn default() -> Self { - Self { - concurrency: 16, - batch: MAX_BATCH, - wait: MAX_WAIT, - visibility: Duration::from_secs(60), - auto_heartbeat: false, - execution_timeout: None, - retry: RetryPolicy::default(), - shutdown_grace: Duration::from_secs(30), - } - } -} - -impl WorkerConfig { - fn validate(&self) -> Result<(), Error> { - if !(1..=Semaphore::MAX_PERMITS).contains(&self.concurrency) { - return Err(Error::InvalidConfig( - "concurrency must be 1..=Semaphore::MAX_PERMITS", - )); - } - if !(1..=MAX_BATCH).contains(&self.batch) { - return Err(Error::InvalidConfig("batch must be 1..=10")); - } - if self.wait.subsec_nanos() != 0 || self.wait.is_zero() || self.wait > MAX_WAIT { - return Err(Error::InvalidConfig( - "wait must be whole seconds in 1..=20 s", - )); - } - if self.visibility.subsec_nanos() != 0 - || self.visibility < Duration::from_secs(2) - || self.visibility > MAX_VISIBILITY - { - return Err(Error::InvalidConfig( - "visibility must be whole seconds in 2 s..=12 h", - )); - } - if self.execution_timeout.is_some_and(|timeout| { - timeout.is_zero() || Instant::now().checked_add(timeout).is_none() - }) { - return Err(Error::InvalidConfig( - "execution_timeout must be greater than zero and representable", - )); - } - if self.auto_heartbeat && self.execution_timeout.is_none() { - return Err(Error::InvalidConfig( - "auto_heartbeat requires execution_timeout", - )); - } - if Instant::now().checked_add(self.shutdown_grace).is_none() { - return Err(Error::InvalidConfig("shutdown_grace must be representable")); - } - if self.retry.max_attempts == Some(0) { - return Err(Error::InvalidConfig("max_attempts must be at least 1")); - } - if self.retry.max.is_some_and(|max| max < self.retry.base) { - return Err(Error::InvalidConfig( - "maximum backoff must be at least the base", - )); - } - Ok(()) - } -} - -trait Handler: Send + Sync { - fn start( - &self, - ctx: Context, - payload: &RawValue, - ) -> Result>, serde_json::Error>; -} - -struct Typed(Arc); - -impl Handler for Typed { - fn start( - &self, - ctx: Context, - payload: &RawValue, - ) -> Result>, serde_json::Error> { - let payload = serde_json::from_str(payload.get())?; - let job = self.0.clone(); - Ok(Box::pin(async move { job.run(ctx, payload).await })) - } -} - -struct AbortOnDrop(JoinHandle); - -impl Drop for AbortOnDrop { - fn drop(&mut self) { - self.0.abort(); - } -} - -struct Shared { - transport: Arc, - config: WorkerConfig, - handler: Box, - queue: &'static str, - dead_letter: Option>, - jobs: CancellationToken, -} - -pub struct Worker { - transport: Arc, - config: WorkerConfig, - handler: Option<(&'static str, Box)>, - dead_letter: Option>, -} - -impl Worker { - pub fn new(transport: Arc, config: WorkerConfig) -> Result { - config.validate()?; - Ok(Self { - transport, - config, - handler: None, - dead_letter: None, - }) - } - - /// Bind the single job handled by this queue. Panics if already bound. - pub fn register(&mut self, job: J) { - assert!(self.handler.is_none(), "a job is already registered"); - self.handler = Some((J::NAME, Box::new(Typed(Arc::new(job))))); - } - - /// Supply a distinct queue for exhausted messages. Delivery to it is at least once. - pub fn set_dead_letter(&mut self, transport: Arc) { - self.dead_letter = Some(transport); - } - - pub async fn run(self, shutdown: CancellationToken) -> Result<(), Error> { - let (queue, handler) = self - .handler - .ok_or(Error::InvalidConfig("no job registered"))?; - if self.config.retry.max_attempts.is_some() && self.dead_letter.is_none() { - return Err(Error::InvalidConfig( - "max_attempts requires a dead-letter queue", - )); - } - if self - .dead_letter - .as_ref() - .is_some_and(|dlq| Arc::ptr_eq(dlq, &self.transport)) - { - return Err(Error::InvalidConfig( - "dead-letter queue must be distinct from the source", - )); - } - let grace = self.config.shutdown_grace; - let shared = Arc::new(Shared { - transport: self.transport, - config: self.config, - handler, - queue, - dead_letter: self.dead_letter, - jobs: CancellationToken::new(), - }); - let permits = Arc::new(Semaphore::new(shared.config.concurrency)); - let mut tasks = JoinSet::new(); - - while let Some(messages) = receive(&shared, &permits, &shutdown).await { - for (message, permit, received_at, receive_started) in messages { - let shared = shared.clone(); - tasks.spawn(async move { - handle(&shared, message, received_at, receive_started).await; - drop(permit); - }); - } - while tasks.try_join_next().is_some() {} - } - - shared.jobs.cancel(); - let drain = async { while tasks.join_next().await.is_some() {} }; - if time::timeout(grace, drain).await.is_err() { - warn!("shutdown grace elapsed, aborting in-flight jobs"); - } - tasks.shutdown().await; - Ok(()) - } -} - -async fn receive( - shared: &Shared, - permits: &Arc, - shutdown: &CancellationToken, -) -> Option< - Vec<( - Received, - tokio::sync::OwnedSemaphorePermit, - Instant, - Instant, - )>, -> { - let config = &shared.config; - let first = tokio::select! { - biased; - _ = shutdown.cancelled() => return None, - permit = permits.clone().acquire_owned() => permit.expect("semaphore is never closed"), - }; - let mut held = vec![first]; - while held.len() < config.batch { - match permits.clone().try_acquire_owned() { - Ok(permit) => held.push(permit), - Err(_) => break, - } - } - let receive_started = Instant::now(); - let result = tokio::select! { - biased; - _ = shutdown.cancelled() => return None, - result = shared.transport.receive(held.len(), config.wait, config.visibility) => result, - }; - match result { - Ok(messages) => { - let received_at = Instant::now(); - Some( - messages - .into_iter() - .zip(held) - .map(|(message, permit)| (message, permit, received_at, receive_started)) - .collect(), - ) - } - Err(e) => { - warn!(error = ?e, "receive failed"); - tokio::select! { - _ = shutdown.cancelled() => None, - _ = time::sleep(RECEIVE_RETRY_DELAY) => Some(Vec::new()), - } - } - } -} - -async fn handle( - shared: &Shared, - message: Received, - received_at: Instant, - receive_started: Instant, -) { - let deadline = received_at + shared.config.visibility; - if shared - .config - .retry - .max_attempts - .is_some_and(|max| message.receive_count > max) - { - if let Err(e) = dead_letter(shared, &message, deadline).await { - warn!(error = ?e, "dead-lettering failed; original message remains in the queue"); - } - return; - } - let payload = match serde_json::from_str::>(&message.body) { - Ok(payload) => payload, - Err(e) => { - warn!(error = %e, receive_count = message.receive_count, "invalid JSON payload"); - if let Err(e) = retry_later(shared, &message, receive_started, deadline).await { - warn!(error = ?e, "disposition failed"); - } - return; - } - }; - let tenant = payload_tenant(&payload); - let span = info_span!( - "job", - name = %shared.queue, - tenant = ?tenant, - receive_count = message.receive_count - ); - process( - shared, - message, - payload, - tenant, - received_at, - receive_started, - ) - .instrument(span) - .await; -} - -fn text_attribute<'a>(message: &'a Received, name: &str) -> Option<&'a str> { - match &message.attributes.get(name)?.value { - AttributeValue::Text(text) => Some(text), - AttributeValue::Binary(_) => None, - } -} - -fn message_headers(message: &Received) -> HashMap { - if let Some(packed) = text_attribute(message, HEADERS_ATTRIBUTE) { - return match serde_json::from_str::(packed) { - Ok(serde_json::Value::Object(headers)) => headers - .into_iter() - .filter_map(|(name, value)| value.as_str().map(|text| (name, text.to_owned()))) - .collect(), - _ => HashMap::new(), - }; - } - message - .attributes - .iter() - .filter_map(|(name, attribute)| { - if name.starts_with("queue.") || attribute.data_type.starts_with("Binary") { - return None; - } - match &attribute.value { - AttributeValue::Text(value) => Some((name.clone(), value.clone())), - AttributeValue::Binary(_) => None, - } - }) - .collect() -} - -async fn process( - shared: &Shared, - message: Received, - payload: Box, - tenant: Option, - received_at: Instant, - receive_started: Instant, -) { - let cancel = shared.jobs.child_token(); - let ctx = Context { - tenant, - receive_count: message.receive_count, - key: text_attribute(&message, KEY_ATTRIBUTE).map(str::to_owned), - headers: message_headers(&message), - cancel: cancel.clone(), - }; - let future = match shared.handler.start(ctx, &payload) { - Ok(future) => future, - Err(e) => { - warn!(error = %e, "invalid payload"); - if let Err(e) = retry_later( - shared, - &message, - receive_started, - received_at + shared.config.visibility, - ) - .await - { - warn!(error = ?e, "disposition failed"); - } - return; - } - }; - let execution_deadline = shared - .config - .execution_timeout - .map(|timeout| Instant::now() + timeout); - let mut job = AbortOnDrop(tokio::spawn(future.in_current_span())); - - let visibility = shared.config.visibility; - let half = visibility / 2; - let mut next_beat = received_at + half; - let mut heartbeat: Option> = None; - let mut lease_deadline = received_at + visibility; - let mut cancel_deadline = None; - let mut timed_out = false; - // Lease-loss branches precede the job so that a ready loss is never ignored. - let joined = loop { - tokio::select! { - biased; - _ = time::sleep_until(lease_deadline) => { - warn!("visibility expired, cancelling job"); - break None; - } - result = async { heartbeat.as_mut().expect("guarded").2.as_mut().await }, if heartbeat.is_some() => { - let (started, duration, _) = heartbeat.take().expect("guarded"); - match result { - Ok(()) => { - lease_deadline = started + duration; - next_beat = started + half; - } - Err(storage_queue_transport::Error::StaleReceipt) => { - warn!("lease lost, cancelling job"); - break None; - } - Err(e) => { - warn!(error = ?e, "heartbeat failed"); - next_beat = Instant::now() + HEARTBEAT_RETRY.min(half); - } - } - } - joined = &mut job.0 => break Some(joined), - _ = async { time::sleep_until(execution_deadline.expect("guarded")).await }, if execution_deadline.is_some() && cancel_deadline.is_none() => { - warn!("job execution timed out, cancelling job"); - cancel.cancel(); - cancel_deadline = Some(Instant::now() + shared.config.shutdown_grace); - } - _ = async { time::sleep_until(cancel_deadline.expect("guarded")).await }, if cancel_deadline.is_some() => { - warn!("job ignored cancellation, aborting"); - job.0.abort(); - let joined = (&mut job.0).await; - timed_out = matches!(&joined, Err(e) if e.is_cancelled()); - break Some(joined); - } - _ = time::sleep_until(next_beat), if shared.config.auto_heartbeat && heartbeat.is_none() => { - let started = Instant::now(); - let duration = visibility.min(remaining_window(receive_started, started)); - if duration.is_zero() { - warn!("visibility window exhausted, cancelling job"); - break None; - } - heartbeat = Some(( - started, - duration, - Box::pin(shared.transport.extend(&message.receipt, duration)), - )); - } - } - }; - let Some(joined) = joined else { - // A lost lease must not settle a delivery that may now be owned elsewhere. - cancel.cancel(); - if time::timeout(shared.config.shutdown_grace, &mut job.0) - .await - .is_err() - { - warn!("job ignored cancellation, aborting"); - } - return; - }; - - if !matches!(joined, Ok(Ok(Disposition::Done))) { - // A late heartbeat would override the retry delay. - if let Some((started, duration, extend)) = heartbeat { - match time::timeout_at(lease_deadline, extend).await { - Ok(Ok(())) => lease_deadline = started + duration, - Ok(Err(storage_queue_transport::Error::StaleReceipt)) => return, - Ok(Err(_)) | Err(_) => {} - } - } - } - if Instant::now() >= lease_deadline { - return; - } - let result = if timed_out { - if shared.jobs.is_cancelled() { - extend(shared, &message, Duration::ZERO, receive_started).await - } else { - retry_later(shared, &message, receive_started, lease_deadline).await - } - } else { - match joined { - Ok(Ok(Disposition::Done)) => shared.transport.delete(&[&message.receipt]).await, - Ok(Ok(Disposition::RetryAfter(delay))) => { - if shared.jobs.is_cancelled() { - extend(shared, &message, Duration::ZERO, receive_started).await - } else if exhausted(shared, &message) { - dead_letter(shared, &message, lease_deadline).await - } else { - extend(shared, &message, delay, receive_started).await - } - } - Ok(Err(e)) => { - error!(error = %e, "job failed"); - if shared.jobs.is_cancelled() { - extend(shared, &message, Duration::ZERO, receive_started).await - } else { - retry_later(shared, &message, receive_started, lease_deadline).await - } - } - Err(e) => { - error!(error = %e, "job panicked"); - retry_later(shared, &message, receive_started, lease_deadline).await - } - } - }; - if let Err(e) = result { - warn!(error = ?e, "disposition failed, message will reappear after visibility timeout"); - } -} - -async fn retry_later( - shared: &Shared, - message: &Received, - receive_started: Instant, - lease_deadline: Instant, -) -> Result<(), storage_queue_transport::Error> { - if exhausted(shared, message) { - dead_letter(shared, message, lease_deadline).await - } else { - extend( - shared, - message, - shared.config.retry.delay(message.receive_count), - receive_started, - ) - .await - } -} - -fn exhausted(shared: &Shared, message: &Received) -> bool { - shared - .config - .retry - .max_attempts - .is_some_and(|max| message.receive_count >= max) -} - -async fn dead_letter( - shared: &Shared, - message: &Received, - lease_deadline: Instant, -) -> Result<(), storage_queue_transport::Error> { - let Some(destination) = &shared.dead_letter else { - return Err(storage_queue_transport::Error::InvalidArgument( - "dead-letter queue is not configured", - )); - }; - let copy = Outgoing { - body: message.body.clone(), - group_id: message.group_id.clone(), - attributes: message.attributes.clone(), - }; - time::timeout_at(lease_deadline, destination.send(&[copy])) - .await - .map_err(|_| storage_queue_transport::Error::StaleReceipt)??; - if Instant::now() >= lease_deadline { - return Err(storage_queue_transport::Error::StaleReceipt); - } - shared.transport.delete(&[&message.receipt]).await -} - -async fn extend( - shared: &Shared, - message: &Received, - delay: Duration, - receive_started: Instant, -) -> Result<(), storage_queue_transport::Error> { - let secs = delay - .as_secs() - .saturating_add(u64::from(delay.subsec_nanos() > 0)); - let remaining = remaining_window(receive_started, Instant::now()).min(MAX_RETRY_DELAY); - let delay = if secs > remaining.as_secs() { - warn!( - requested_seconds = secs, - remaining_seconds = remaining.as_secs(), - "retry delay shortened to the supported visibility window" - ); - remaining - } else { - Duration::from_secs(secs) - }; - shared.transport.extend(&message.receipt, delay).await -} - -fn remaining_window(receive_started: Instant, now: Instant) -> Duration { - let remaining = - (receive_started + MAX_VISIBILITY - VISIBILITY_MARGIN).saturating_duration_since(now); - Duration::from_secs(remaining.as_secs()) -} +mod config; +mod job; +mod message; +mod worker; + +pub use config::{Backoff, RetryPolicy, WorkerConfig}; +pub use job::{BoxError, Context, Disposition, Error, Job}; +pub use message::{EncodeOptions, encode, encode_with_options}; +pub use worker::Worker; diff --git a/rust/crates/queue/src/message.rs b/rust/crates/queue/src/message.rs new file mode 100644 index 000000000..58adba5e4 --- /dev/null +++ b/rust/crates/queue/src/message.rs @@ -0,0 +1,116 @@ +use std::collections::HashMap; + +use serde_json::value::RawValue; +use sha2::{Digest, Sha256}; +use storage_queue_transport::{AttributeValue, MessageAttribute, Outgoing, Received}; + +use crate::{Error, Job}; + +const SYSTEM_TENANT_REF: &str = "SYSTEM_TENANT"; +const HEADERS_ATTRIBUTE: &str = "queue.headers"; +pub(crate) const KEY_ATTRIBUTE: &str = "queue.key"; + +pub(crate) fn payload_tenant(payload: &RawValue) -> Option { + let value = serde_json::from_str::(payload.get()).ok()?; + value.get("tenant")?.get("ref")?.as_str().map(str::to_owned) +} + +fn string_attribute(value: String) -> MessageAttribute { + MessageAttribute { + data_type: "String".into(), + value: AttributeValue::Text(value), + } +} + +fn group_id(key: &str) -> String { + if !key.is_empty() && key.len() <= 128 && key.bytes().all(|b| (0x21..=0x7e).contains(&b)) { + key.to_owned() + } else { + use std::fmt::Write; + let mut result = String::from("sha256:"); + for byte in Sha256::digest(key.as_bytes()) { + write!(&mut result, "{byte:02x}").expect("writing to a string cannot fail"); + } + result + } +} + +#[derive(Debug, Default)] +pub struct EncodeOptions<'a> { + /// Override the key derived from the payload's tenant reference. + pub key: Option<&'a str>, + /// Used as a fair-queue group when there is no key. Standard SQS does not deduplicate it. + pub idempotency_key: Option<&'a str>, + pub headers: HashMap, +} + +/// Encode the bare JSON body and manager attributes for this job's queue. +pub fn encode(payload: &J::Payload) -> Result { + encode_with_options::(payload, EncodeOptions::default()) +} + +pub fn encode_with_options( + payload: &J::Payload, + options: EncodeOptions<'_>, +) -> Result { + let payload = serde_json::value::to_raw_value(payload)?; + let tenant = payload_tenant(&payload).filter(|t| t != SYSTEM_TENANT_REF); + let key = options + .key + .or(tenant.as_deref()) + .filter(|key| !key.is_empty()); + let fair_group = key.or(options.idempotency_key.filter(|key| !key.is_empty())); + let mut attributes = HashMap::new(); + if let Some(key) = key { + attributes.insert(KEY_ATTRIBUTE.into(), string_attribute(key.to_owned())); + } + let mut headers = options.headers; + if let Some(kind) = J::TYPE { + headers + .entry("message-type".into()) + .or_insert_with(|| kind.to_owned()); + } + if !headers.is_empty() { + attributes.insert( + HEADERS_ATTRIBUTE.into(), + string_attribute(serde_json::to_string(&headers)?), + ); + } + Ok(Outgoing { + body: payload.get().to_owned(), + group_id: fair_group.map(group_id), + attributes, + }) +} + +pub(crate) fn text_attribute<'a>(message: &'a Received, name: &str) -> Option<&'a str> { + match &message.attributes.get(name)?.value { + AttributeValue::Text(text) => Some(text), + AttributeValue::Binary(_) => None, + } +} + +pub(crate) fn message_headers(message: &Received) -> HashMap { + if let Some(packed) = text_attribute(message, HEADERS_ATTRIBUTE) { + return match serde_json::from_str::(packed) { + Ok(serde_json::Value::Object(headers)) => headers + .into_iter() + .filter_map(|(name, value)| value.as_str().map(|text| (name, text.to_owned()))) + .collect(), + _ => HashMap::new(), + }; + } + message + .attributes + .iter() + .filter_map(|(name, attribute)| { + if name.starts_with("queue.") || attribute.data_type.starts_with("Binary") { + return None; + } + match &attribute.value { + AttributeValue::Text(value) => Some((name.clone(), value.clone())), + AttributeValue::Binary(_) => None, + } + }) + .collect() +} diff --git a/rust/crates/queue/src/worker.rs b/rust/crates/queue/src/worker.rs new file mode 100644 index 000000000..48fcf9497 --- /dev/null +++ b/rust/crates/queue/src/worker.rs @@ -0,0 +1,191 @@ +mod process; +mod settlement; + +use std::{future::Future, pin::Pin, sync::Arc, time::Duration}; + +use serde_json::value::RawValue; +use storage_queue_transport::{Received, Transport}; +use tokio::{ + sync::Semaphore, + task::{JoinHandle, JoinSet}, + time::{self, Instant}, +}; +use tokio_util::sync::CancellationToken; +use tracing::warn; + +use crate::{BoxError, Context, Disposition, Error, Job, WorkerConfig}; +use process::handle; + +type BoxFuture = Pin + Send>>; +const RECEIVE_RETRY_DELAY: Duration = Duration::from_secs(1); + +trait Handler: Send + Sync { + fn start( + &self, + ctx: Context, + payload: &RawValue, + ) -> Result>, serde_json::Error>; +} + +struct Typed(Arc); + +impl Handler for Typed { + fn start( + &self, + ctx: Context, + payload: &RawValue, + ) -> Result>, serde_json::Error> { + let payload = serde_json::from_str(payload.get())?; + let job = self.0.clone(); + Ok(Box::pin(async move { job.run(ctx, payload).await })) + } +} + +struct AbortOnDrop(JoinHandle); + +impl Drop for AbortOnDrop { + fn drop(&mut self) { + self.0.abort(); + } +} + +struct Shared { + transport: Arc, + config: WorkerConfig, + handler: Box, + queue: &'static str, + dead_letter: Option>, + jobs: CancellationToken, +} + +pub struct Worker { + transport: Arc, + config: WorkerConfig, + handler: Option<(&'static str, Box)>, + dead_letter: Option>, +} + +impl Worker { + pub fn new(transport: Arc, config: WorkerConfig) -> Result { + config.validate()?; + Ok(Self { + transport, + config, + handler: None, + dead_letter: None, + }) + } + + /// Bind the single job handled by this queue. Panics if already bound. + pub fn register(&mut self, job: J) { + assert!(self.handler.is_none(), "a job is already registered"); + self.handler = Some((J::NAME, Box::new(Typed(Arc::new(job))))); + } + + /// Supply a distinct queue for exhausted messages. Delivery to it is at least once. + pub fn set_dead_letter(&mut self, transport: Arc) { + self.dead_letter = Some(transport); + } + + pub async fn run(self, shutdown: CancellationToken) -> Result<(), Error> { + let (queue, handler) = self + .handler + .ok_or(Error::InvalidConfig("no job registered"))?; + if self.config.retry.max_attempts.is_some() && self.dead_letter.is_none() { + return Err(Error::InvalidConfig( + "max_attempts requires a dead-letter queue", + )); + } + if self + .dead_letter + .as_ref() + .is_some_and(|dlq| Arc::ptr_eq(dlq, &self.transport)) + { + return Err(Error::InvalidConfig( + "dead-letter queue must be distinct from the source", + )); + } + let grace = self.config.shutdown_grace; + let shared = Arc::new(Shared { + transport: self.transport, + config: self.config, + handler, + queue, + dead_letter: self.dead_letter, + jobs: CancellationToken::new(), + }); + let permits = Arc::new(Semaphore::new(shared.config.concurrency)); + let mut tasks = JoinSet::new(); + + while let Some(messages) = receive(&shared, &permits, &shutdown).await { + for (message, permit, received_at, receive_started) in messages { + let shared = shared.clone(); + tasks.spawn(async move { + handle(&shared, message, received_at, receive_started).await; + drop(permit); + }); + } + while tasks.try_join_next().is_some() {} + } + + shared.jobs.cancel(); + let drain = async { while tasks.join_next().await.is_some() {} }; + if time::timeout(grace, drain).await.is_err() { + warn!("shutdown grace elapsed, aborting in-flight jobs"); + } + tasks.shutdown().await; + Ok(()) + } +} + +async fn receive( + shared: &Shared, + permits: &Arc, + shutdown: &CancellationToken, +) -> Option< + Vec<( + Received, + tokio::sync::OwnedSemaphorePermit, + Instant, + Instant, + )>, +> { + let config = &shared.config; + let first = tokio::select! { + biased; + _ = shutdown.cancelled() => return None, + permit = permits.clone().acquire_owned() => permit.expect("semaphore is never closed"), + }; + let mut held = vec![first]; + while held.len() < config.batch { + match permits.clone().try_acquire_owned() { + Ok(permit) => held.push(permit), + Err(_) => break, + } + } + let receive_started = Instant::now(); + let result = tokio::select! { + biased; + _ = shutdown.cancelled() => return None, + result = shared.transport.receive(held.len(), config.wait, config.visibility) => result, + }; + match result { + Ok(messages) => { + let received_at = Instant::now(); + Some( + messages + .into_iter() + .zip(held) + .map(|(message, permit)| (message, permit, received_at, receive_started)) + .collect(), + ) + } + Err(e) => { + warn!(error = ?e, "receive failed"); + tokio::select! { + _ = shutdown.cancelled() => None, + _ = time::sleep(RECEIVE_RETRY_DELAY) => Some(Vec::new()), + } + } + } +} diff --git a/rust/crates/queue/src/worker/process.rs b/rust/crates/queue/src/worker/process.rs new file mode 100644 index 000000000..c2d31f2a1 --- /dev/null +++ b/rust/crates/queue/src/worker/process.rs @@ -0,0 +1,230 @@ +use std::{future::Future, pin::Pin, time::Duration}; + +use serde_json::value::RawValue; +use storage_queue_transport::{Received, Transport}; +use tokio::time::{self, Instant}; +use tracing::{Instrument, error, info_span, warn}; + +use super::{ + AbortOnDrop, Shared, + settlement::{dead_letter, exhausted, extend, remaining_window, retry_later}, +}; +use crate::{ + Context, Disposition, + message::{KEY_ATTRIBUTE, message_headers, payload_tenant, text_attribute}, +}; + +type Heartbeat<'a> = ( + Instant, + Duration, + Pin> + Send + 'a>>, +); +const HEARTBEAT_RETRY: Duration = Duration::from_secs(1); + +pub(super) async fn handle( + shared: &Shared, + message: Received, + received_at: Instant, + receive_started: Instant, +) { + let deadline = received_at + shared.config.visibility; + if shared + .config + .retry + .max_attempts + .is_some_and(|max| message.receive_count > max) + { + if let Err(e) = dead_letter(shared, &message, deadline).await { + warn!(error = ?e, "dead-lettering failed; original message remains in the queue"); + } + return; + } + let payload = match serde_json::from_str::>(&message.body) { + Ok(payload) => payload, + Err(e) => { + warn!(error = %e, receive_count = message.receive_count, "invalid JSON payload"); + if let Err(e) = retry_later(shared, &message, receive_started, deadline).await { + warn!(error = ?e, "disposition failed"); + } + return; + } + }; + let tenant = payload_tenant(&payload); + let span = info_span!( + "job", + name = %shared.queue, + tenant = ?tenant, + receive_count = message.receive_count + ); + process( + shared, + message, + payload, + tenant, + received_at, + receive_started, + ) + .instrument(span) + .await; +} + +async fn process( + shared: &Shared, + message: Received, + payload: Box, + tenant: Option, + received_at: Instant, + receive_started: Instant, +) { + let cancel = shared.jobs.child_token(); + let ctx = Context { + tenant, + receive_count: message.receive_count, + key: text_attribute(&message, KEY_ATTRIBUTE).map(str::to_owned), + headers: message_headers(&message), + cancel: cancel.clone(), + }; + let future = match shared.handler.start(ctx, &payload) { + Ok(future) => future, + Err(e) => { + warn!(error = %e, "invalid payload"); + if let Err(e) = retry_later( + shared, + &message, + receive_started, + received_at + shared.config.visibility, + ) + .await + { + warn!(error = ?e, "disposition failed"); + } + return; + } + }; + let execution_deadline = shared + .config + .execution_timeout + .map(|timeout| Instant::now() + timeout); + let mut job = AbortOnDrop(tokio::spawn(future.in_current_span())); + + let visibility = shared.config.visibility; + let half = visibility / 2; + let mut next_beat = received_at + half; + let mut heartbeat: Option> = None; + let mut lease_deadline = received_at + visibility; + let mut cancel_deadline = None; + let mut timed_out = false; + // Lease-loss branches precede the job so that a ready loss is never ignored. + let joined = loop { + tokio::select! { + biased; + _ = time::sleep_until(lease_deadline) => { + warn!("visibility expired, cancelling job"); + break None; + } + result = async { heartbeat.as_mut().expect("guarded").2.as_mut().await }, if heartbeat.is_some() => { + let (started, duration, _) = heartbeat.take().expect("guarded"); + match result { + Ok(()) => { + lease_deadline = started + duration; + next_beat = started + half; + } + Err(storage_queue_transport::Error::StaleReceipt) => { + warn!("lease lost, cancelling job"); + break None; + } + Err(e) => { + warn!(error = ?e, "heartbeat failed"); + next_beat = Instant::now() + HEARTBEAT_RETRY.min(half); + } + } + } + joined = &mut job.0 => break Some(joined), + _ = async { time::sleep_until(execution_deadline.expect("guarded")).await }, if execution_deadline.is_some() && cancel_deadline.is_none() => { + warn!("job execution timed out, cancelling job"); + cancel.cancel(); + cancel_deadline = Some(Instant::now() + shared.config.shutdown_grace); + } + _ = async { time::sleep_until(cancel_deadline.expect("guarded")).await }, if cancel_deadline.is_some() => { + warn!("job ignored cancellation, aborting"); + job.0.abort(); + let joined = (&mut job.0).await; + timed_out = matches!(&joined, Err(e) if e.is_cancelled()); + break Some(joined); + } + _ = time::sleep_until(next_beat), if shared.config.auto_heartbeat && heartbeat.is_none() => { + let started = Instant::now(); + let duration = visibility.min(remaining_window(receive_started, started)); + if duration.is_zero() { + warn!("visibility window exhausted, cancelling job"); + break None; + } + heartbeat = Some(( + started, + duration, + Box::pin(shared.transport.extend(&message.receipt, duration)), + )); + } + } + }; + let Some(joined) = joined else { + // A lost lease must not settle a delivery that may now be owned elsewhere. + cancel.cancel(); + if time::timeout(shared.config.shutdown_grace, &mut job.0) + .await + .is_err() + { + warn!("job ignored cancellation, aborting"); + } + return; + }; + + if !matches!(joined, Ok(Ok(Disposition::Done))) { + // A late heartbeat would override the retry delay. + if let Some((started, duration, extend)) = heartbeat { + match time::timeout_at(lease_deadline, extend).await { + Ok(Ok(())) => lease_deadline = started + duration, + Ok(Err(storage_queue_transport::Error::StaleReceipt)) => return, + Ok(Err(_)) | Err(_) => {} + } + } + } + if Instant::now() >= lease_deadline { + return; + } + let result = if timed_out { + if shared.jobs.is_cancelled() { + extend(shared, &message, Duration::ZERO, receive_started).await + } else { + retry_later(shared, &message, receive_started, lease_deadline).await + } + } else { + match joined { + Ok(Ok(Disposition::Done)) => shared.transport.delete(&[&message.receipt]).await, + Ok(Ok(Disposition::RetryAfter(delay))) => { + if shared.jobs.is_cancelled() { + extend(shared, &message, Duration::ZERO, receive_started).await + } else if exhausted(shared, &message) { + dead_letter(shared, &message, lease_deadline).await + } else { + extend(shared, &message, delay, receive_started).await + } + } + Ok(Err(e)) => { + error!(error = %e, "job failed"); + if shared.jobs.is_cancelled() { + extend(shared, &message, Duration::ZERO, receive_started).await + } else { + retry_later(shared, &message, receive_started, lease_deadline).await + } + } + Err(e) => { + error!(error = %e, "job panicked"); + retry_later(shared, &message, receive_started, lease_deadline).await + } + } + }; + if let Err(e) = result { + warn!(error = ?e, "disposition failed, message will reappear after visibility timeout"); + } +} diff --git a/rust/crates/queue/src/worker/settlement.rs b/rust/crates/queue/src/worker/settlement.rs new file mode 100644 index 000000000..50e143398 --- /dev/null +++ b/rust/crates/queue/src/worker/settlement.rs @@ -0,0 +1,91 @@ +use std::time::Duration; + +use storage_queue_transport::{Outgoing, Received, Transport}; +use tokio::time::{self, Instant}; +use tracing::warn; + +use super::Shared; +use crate::config::{MAX_RETRY_DELAY, MAX_VISIBILITY}; + +// Leave time for the visibility request to reach SQS before its 12-hour deadline. +const VISIBILITY_MARGIN: Duration = Duration::from_secs(5); + +pub(super) async fn retry_later( + shared: &Shared, + message: &Received, + receive_started: Instant, + lease_deadline: Instant, +) -> Result<(), storage_queue_transport::Error> { + if exhausted(shared, message) { + dead_letter(shared, message, lease_deadline).await + } else { + extend( + shared, + message, + shared.config.retry.delay(message.receive_count), + receive_started, + ) + .await + } +} + +pub(super) fn exhausted(shared: &Shared, message: &Received) -> bool { + shared + .config + .retry + .max_attempts + .is_some_and(|max| message.receive_count >= max) +} + +pub(super) async fn dead_letter( + shared: &Shared, + message: &Received, + lease_deadline: Instant, +) -> Result<(), storage_queue_transport::Error> { + let Some(destination) = &shared.dead_letter else { + return Err(storage_queue_transport::Error::InvalidArgument( + "dead-letter queue is not configured", + )); + }; + let copy = Outgoing { + body: message.body.clone(), + group_id: message.group_id.clone(), + attributes: message.attributes.clone(), + }; + time::timeout_at(lease_deadline, destination.send(&[copy])) + .await + .map_err(|_| storage_queue_transport::Error::StaleReceipt)??; + if Instant::now() >= lease_deadline { + return Err(storage_queue_transport::Error::StaleReceipt); + } + shared.transport.delete(&[&message.receipt]).await +} + +pub(super) async fn extend( + shared: &Shared, + message: &Received, + delay: Duration, + receive_started: Instant, +) -> Result<(), storage_queue_transport::Error> { + let secs = delay + .as_secs() + .saturating_add(u64::from(delay.subsec_nanos() > 0)); + let remaining = remaining_window(receive_started, Instant::now()).min(MAX_RETRY_DELAY); + let delay = if secs > remaining.as_secs() { + warn!( + requested_seconds = secs, + remaining_seconds = remaining.as_secs(), + "retry delay shortened to the supported visibility window" + ); + remaining + } else { + Duration::from_secs(secs) + }; + shared.transport.extend(&message.receipt, delay).await +} + +pub(super) fn remaining_window(receive_started: Instant, now: Instant) -> Duration { + let remaining = + (receive_started + MAX_VISIBILITY - VISIBILITY_MARGIN).saturating_duration_since(now); + Duration::from_secs(remaining.as_secs()) +} diff --git a/rust/crates/queue/tests/sqs.rs b/rust/crates/queue/tests/sqs.rs index aa73aae04..7ac11c7fb 100644 --- a/rust/crates/queue/tests/sqs.rs +++ b/rust/crates/queue/tests/sqs.rs @@ -18,7 +18,7 @@ use storage_queue_transport::{Transport, sqs::SqsQueue}; use tokio::time::{Instant, sleep}; use tokio_util::sync::CancellationToken; -const SQS_ENDPOINT: &str = "STORAGE_QUEUE_TEST_SQS_ENDPOINT"; +const SQS_ENDPOINT: &str = "QUEUE_TEST_SQS_ENDPOINT"; static NEXT_QUEUE: AtomicUsize = AtomicUsize::new(0); #[derive(Serialize, Deserialize)] @@ -51,8 +51,7 @@ impl Job for Echo { } async fn queue() -> SqsQueue { - let endpoint = - std::env::var(SQS_ENDPOINT).expect("STORAGE_QUEUE_TEST_SQS_ENDPOINT must be set"); + let endpoint = std::env::var(SQS_ENDPOINT).expect("QUEUE_TEST_SQS_ENDPOINT must be set"); let config = aws_sdk_sqs::Config::builder() .behavior_version(BehaviorVersion::latest()) .endpoint_url(endpoint) From dea1625023465ad514b168a89dff08f63dfcbdea Mon Sep 17 00:00:00 2001 From: Ferhat Elmas Date: Fri, 13 Nov 2026 12:11:43 +0100 Subject: [PATCH 4/4] refactor: port node batch algo Signed-off-by: Ferhat Elmas --- rust/README.md | 5 + rust/crates/queue-transport/src/lib.rs | 22 + rust/crates/queue-transport/src/sqs.rs | 63 ++- .../queue-transport/src/sqs/visibility.rs | 97 ++++ rust/crates/queue-transport/tests/contract.rs | 54 +- .../queue-transport/tests/failure_paths.rs | 61 ++ rust/crates/queue/src/config.rs | 10 +- rust/crates/queue/src/worker.rs | 106 ++-- rust/crates/queue/src/worker/pull.rs | 273 +++++++++ rust/crates/queue/src/worker/wait.rs | 68 +++ rust/crates/queue/tests/pull.rs | 532 ++++++++++++++++++ rust/crates/queue/tests/sqs.rs | 44 ++ rust/crates/queue/tests/worker.rs | 12 +- 13 files changed, 1280 insertions(+), 67 deletions(-) create mode 100644 rust/crates/queue-transport/src/sqs/visibility.rs create mode 100644 rust/crates/queue/src/worker/pull.rs create mode 100644 rust/crates/queue/src/worker/wait.rs create mode 100644 rust/crates/queue/tests/pull.rs diff --git a/rust/README.md b/rust/README.md index 63aa9974d..1bcf8365c 100644 --- a/rust/README.md +++ b/rust/README.md @@ -8,6 +8,11 @@ Jobs use the Node queue manager's bare JSON payload and message attributes. Each one job type on one queue. Tenant keys are used as SQS message groups for fair queues; this does not guarantee ordering or deduplication. All consumers of a queue must support its payloads. +`WorkerConfig::batch` controls prefetch, independently of handler `concurrency`. A full initial +receive triggers parallel short polls; late responses are renewed before the next pull. Set the +visibility timeout and heartbeats to cover time spent waiting for a handler slot. Late fill results +can be held outside the prefetch window until the next pull. + Configure visibility, execution timeout, retry policy, and dead-letter settings consistently across workers sharing a queue. Set retry backoff and attempt limits with `WorkerConfig::retry`. An attempt limit requires a distinct dead-letter queue supplied through `set_dead_letter`. Provision queues diff --git a/rust/crates/queue-transport/src/lib.rs b/rust/crates/queue-transport/src/lib.rs index 43da26524..bfdc8cefb 100644 --- a/rust/crates/queue-transport/src/lib.rs +++ b/rust/crates/queue-transport/src/lib.rs @@ -28,6 +28,7 @@ pub struct Outgoing { #[derive(Debug, Clone)] pub struct Received { + pub id: String, pub receipt: String, pub body: String, pub receive_count: u32, @@ -65,6 +66,27 @@ pub trait Transport { receipt: &str, visibility: Duration, ) -> impl Future> + Send; + /// Change visibility for several receipts, returning whether each was accepted. + fn extend_batch( + &self, + receipts: &[&str], + visibility: Duration, + ) -> impl Future, Error>> + Send + where + Self: Sync, + { + async move { + let mut accepted = Vec::with_capacity(receipts.len()); + for receipt in receipts { + match self.extend(receipt, visibility).await { + Ok(()) => accepted.push(true), + Err(Error::StaleReceipt) => accepted.push(false), + Err(error) => return Err(error), + } + } + Ok(accepted) + } + } /// Delete (ack). SQS may report success for an old receipt without deleting the message; /// rejected receipts are reported as failures. /// Batch errors report an outcome for each input. diff --git a/rust/crates/queue-transport/src/sqs.rs b/rust/crates/queue-transport/src/sqs.rs index 7ba219c0a..f0dbfdb51 100644 --- a/rust/crates/queue-transport/src/sqs.rs +++ b/rust/crates/queue-transport/src/sqs.rs @@ -1,4 +1,6 @@ -use std::time::Duration; +mod visibility; + +use std::{collections::HashMap, time::Duration}; use aws_sdk_sqs::{ Client, @@ -17,7 +19,9 @@ use crate::{ const BATCH: usize = 10; const MAX_BATCH_BYTES: usize = 1024 * 1024; +const SETTLE_CONCURRENCY: usize = 4; +#[derive(Clone)] pub struct SqsQueue { client: Client, queue_url: String, @@ -85,6 +89,10 @@ fn received(m: &Message) -> Result { .filter(|count| *count > 0) .ok_or(Error::InvalidResponse("invalid receive count"))?; Ok(Received { + id: m + .message_id() + .ok_or(Error::InvalidResponse("missing message id"))? + .to_owned(), receipt: m .receipt_handle() .ok_or(Error::InvalidResponse("missing receipt handle"))? @@ -279,6 +287,49 @@ impl Transport for SqsQueue { Ok(()) } + async fn extend_batch( + &self, + receipts: &[&str], + visibility: Duration, + ) -> Result, Error> { + check_visibility(visibility)?; + let mut positions = HashMap::new(); + let mut unique = Vec::new(); + let indexes: Vec = receipts + .iter() + .map(|receipt| { + *positions.entry(*receipt).or_insert_with(|| { + let index = unique.len(); + unique.push(*receipt); + index + }) + }) + .collect(); + let mut pending = tokio::task::JoinSet::new(); + let mut batches = unique.chunks(BATCH).enumerate(); + let mut accepted = vec![false; unique.len()]; + loop { + while pending.len() < SETTLE_CONCURRENCY { + let Some((index, chunk)) = batches.next() else { + break; + }; + let queue = self.clone(); + let chunk: Vec = + chunk.iter().map(|receipt| (*receipt).to_owned()).collect(); + pending.spawn(async move { + (index * BATCH, queue.extend_chunk(&chunk, visibility).await) + }); + } + let Some(result) = pending.join_next().await else { + break; + }; + let (start, chunk) = result.map_err(sqs)?; + let chunk = chunk?; + accepted[start..start + chunk.len()].copy_from_slice(&chunk); + } + Ok(indexes.into_iter().map(|index| accepted[index]).collect()) + } + async fn delete(&self, receipts: &[&str]) -> Result<(), Error> { let mut outcomes = vec![BatchOutcome::NotAttempted; receipts.len()]; for (chunk_index, chunk) in receipts.chunks(BATCH).enumerate() { @@ -347,6 +398,7 @@ mod tests { fn received_requires_message_fields_and_a_valid_count() { let make = |receipt: Option<&str>, body: Option<&str>, count: Option<&str>| { let mut builder = Message::builder() + .message_id("message-id") .set_receipt_handle(receipt.map(str::to_owned)) .set_body(body.map(str::to_owned)); if let Some(count) = count { @@ -363,6 +415,15 @@ mod tests { received(&make(Some("receipt"), None, Some("1"))), Err(Error::InvalidResponse("missing message body")) )); + let without_id = Message::builder() + .receipt_handle("receipt") + .body("body") + .attributes(MessageSystemAttributeName::ApproximateReceiveCount, "1") + .build(); + assert!(matches!( + received(&without_id), + Err(Error::InvalidResponse("missing message id")) + )); for count in [None, Some("invalid"), Some("0")] { assert!(matches!( received(&make(Some("receipt"), Some("body"), count)), diff --git a/rust/crates/queue-transport/src/sqs/visibility.rs b/rust/crates/queue-transport/src/sqs/visibility.rs new file mode 100644 index 000000000..02f3681ba --- /dev/null +++ b/rust/crates/queue-transport/src/sqs/visibility.rs @@ -0,0 +1,97 @@ +use std::time::Duration; + +use aws_sdk_sqs::{error::ProvideErrorMetadata, types::ChangeMessageVisibilityBatchRequestEntry}; + +use super::{SqsQueue, batch_error, record_outcome, secs, sqs}; +use crate::{BatchOutcome, Error, Transport}; + +fn stale_code(code: &str) -> bool { + let code = code.strip_prefix("AWS.SimpleQueueService.").unwrap_or(code); + let code = code.strip_suffix("Exception").unwrap_or(code); + matches!( + code, + "ReceiptHandleIsInvalid" | "MessageNotInflight" | "InvalidParameterValue" + ) +} + +impl SqsQueue { + pub(super) async fn extend_chunk( + &self, + receipts: &[String], + visibility: Duration, + ) -> Result, Error> { + let entries = receipts + .iter() + .enumerate() + .map(|(index, receipt)| { + ChangeMessageVisibilityBatchRequestEntry::builder() + .id(index.to_string()) + .receipt_handle(receipt) + .visibility_timeout(secs(visibility)) + .build() + }) + .collect::, _>>() + .map_err(sqs)?; + let response = self + .client + .change_message_visibility_batch() + .queue_url(&self.queue_url) + .set_entries(Some(entries)) + .send() + .await; + let response = match response { + Ok(response) => response, + Err(error) if error.code().is_some_and(stale_code) => { + let mut accepted = Vec::with_capacity(receipts.len()); + for receipt in receipts { + match self.extend(receipt, visibility).await { + Ok(()) => accepted.push(true), + Err(Error::StaleReceipt) => accepted.push(false), + Err(Error::VisibilityChange { ref code, .. }) + if code.as_deref().is_some_and(stale_code) => + { + accepted.push(false) + } + Err(error) => return Err(error), + } + } + return Ok(accepted); + } + Err(error) => return Err(sqs(error)), + }; + let mut outcomes = vec![BatchOutcome::Unknown; receipts.len()]; + for item in response.successful() { + record_outcome( + &mut outcomes, + 0, + receipts.len(), + item.id(), + BatchOutcome::Succeeded, + )?; + } + for item in response.failed() { + record_outcome( + &mut outcomes, + 0, + receipts.len(), + item.id(), + BatchOutcome::Failed { + code: item.code().to_owned(), + message: item.message().map(str::to_owned), + sender_fault: item.sender_fault(), + }, + )?; + } + if outcomes.iter().any(|outcome| match outcome { + BatchOutcome::Succeeded => false, + BatchOutcome::Failed { code, .. } => !stale_code(code), + _ => true, + }) { + return Err(batch_error("extend", outcomes, None)); + } + Ok(outcomes + .iter() + .map(|outcome| matches!(outcome, BatchOutcome::Succeeded)) + .collect()) + } +} diff --git a/rust/crates/queue-transport/tests/contract.rs b/rust/crates/queue-transport/tests/contract.rs index d1a0468c6..3ef361f95 100644 --- a/rust/crates/queue-transport/tests/contract.rs +++ b/rust/crates/queue-transport/tests/contract.rs @@ -142,6 +142,7 @@ async fn round_trip(q: &T) { .unwrap(); let got = receive_one(q, S2).await; assert_eq!(got.body, "hello"); + assert!(!got.id.is_empty()); assert_eq!(got.receive_count, 1); assert_eq!(got.group_id.as_deref(), Some("g1")); assert_eq!(got.attributes, attributes); @@ -150,11 +151,12 @@ sqs_contract!(round_trip); async fn redelivery(q: &T) { q.send(&[msg("a")]).await.unwrap(); - receive_one(q, S2).await; + let first = receive_one(q, S2).await; assert_empty(q).await; sleep(Duration::from_millis(2500)).await; let got = receive_one(q, S2).await; assert_eq!((got.body.as_str(), got.receive_count), ("a", 2)); + assert_eq!(got.id, first.id); } sqs_contract!(redelivery); @@ -297,3 +299,53 @@ async fn validation_sqs() { let q = SqsQueue::new(sqs_client("http://127.0.0.1:1"), "http://127.0.0.1:1/q"); validation(&q).await; } + +#[tokio::test] +#[ignore = "requires an SQS-compatible endpoint"] +async fn visibility_batch_handles_more_than_ten_messages() { + let queue = sqs_queue("visibility-batch").await; + let messages: Vec<_> = (0..25).map(|i| msg(&format!("m{i}"))).collect(); + queue.send(&messages).await.unwrap(); + let mut received = Vec::new(); + for _ in 0..20 { + if received.len() == messages.len() { + break; + } + received.extend( + queue + .receive(10, S1, Duration::from_secs(30)) + .await + .unwrap(), + ); + } + assert_eq!(received.len(), messages.len()); + let receipts: Vec<_> = received + .iter() + .map(|message| message.receipt.as_str()) + .collect(); + assert_eq!( + queue + .extend_batch(&receipts, Duration::from_secs(60)) + .await + .unwrap(), + vec![true; 25] + ); + assert_eq!( + queue.extend_batch(&receipts, NOW).await.unwrap(), + vec![true; 25] + ); + let mut redelivered = Vec::new(); + for _ in 0..20 { + if redelivered.len() == messages.len() { + break; + } + redelivered.extend( + queue + .receive(10, S1, Duration::from_secs(30)) + .await + .unwrap(), + ); + } + assert_eq!(redelivered.len(), messages.len()); + assert!(redelivered.iter().all(|message| message.receive_count == 2)); +} diff --git a/rust/crates/queue-transport/tests/failure_paths.rs b/rust/crates/queue-transport/tests/failure_paths.rs index 17db669ad..31f1b1bc3 100644 --- a/rust/crates/queue-transport/tests/failure_paths.rs +++ b/rust/crates/queue-transport/tests/failure_paths.rs @@ -366,3 +366,64 @@ async fn duplicate_batch_ids_leave_the_chunk_unknown() { vec![BatchOutcome::Unknown, BatchOutcome::Unknown] ); } + +#[tokio::test] +async fn visibility_batch_retains_successes_when_a_receipt_is_stale() { + let body = r#"{"Successful":[{"Id":"0"}],"Failed":[{"Id":"1","Code":"ReceiptHandleIsInvalid","SenderFault":true}]}"#; + let (queue, server) = endpoint(vec![(200, body.into())]); + let result = queue + .extend_batch(&["valid", "stale"], Duration::from_secs(60)) + .await + .unwrap(); + let requests = server.join().unwrap(); + assert_eq!(result, [true, false]); + assert_eq!(requests[0].matches("\"ReceiptHandle\"").count(), 2); + assert_eq!(requests[0].matches("\"VisibilityTimeout\":60").count(), 2); +} + +#[tokio::test] +async fn visibility_batch_rejects_an_incomplete_response() { + let (queue, server) = endpoint(vec![( + 200, + r#"{"Successful":[{"Id":"0"}],"Failed":[]}"#.into(), + )]); + assert!(matches!( + queue + .extend_batch(&["first", "second"], Duration::from_secs(60)) + .await, + Err(Error::Batch(_)) + )); + server.join().unwrap(); +} + +#[tokio::test] +async fn visibility_batch_deduplicates_receipt_handles() { + let (queue, server) = endpoint(vec![( + 200, + r#"{"Successful":[{"Id":"0"}],"Failed":[]}"#.into(), + )]); + let result = queue + .extend_batch(&["same", "same"], Duration::from_secs(60)) + .await + .unwrap(); + let requests = server.join().unwrap(); + assert_eq!(result, [true, true]); + assert_eq!(requests[0].matches("\"ReceiptHandle\"").count(), 1); +} + +#[tokio::test] +async fn visibility_batch_retries_individually_if_the_whole_batch_has_a_stale_receipt() { + let stale = r#"{"__type":"ReceiptHandleIsInvalid","message":"invalid receipt"}"#; + let (queue, server) = endpoint(vec![ + (400, stale.into()), + (200, "{}".into()), + (400, stale.into()), + ]); + let accepted = queue + .extend_batch(&["valid", "stale"], Duration::from_secs(60)) + .await + .unwrap(); + let requests = server.join().unwrap(); + assert_eq!(accepted, [true, false]); + assert_eq!(requests.len(), 3); +} diff --git a/rust/crates/queue/src/config.rs b/rust/crates/queue/src/config.rs index 7807fe204..56fa43b59 100644 --- a/rust/crates/queue/src/config.rs +++ b/rust/crates/queue/src/config.rs @@ -4,7 +4,6 @@ use tokio::{sync::Semaphore, time::Instant}; use crate::Error; -const MAX_BATCH: usize = 10; const MAX_WAIT: Duration = Duration::from_secs(20); pub(crate) const MAX_VISIBILITY: Duration = Duration::from_secs(12 * 60 * 60); // Matches the Node SQS adapter's cap on parked retries. @@ -13,6 +12,7 @@ pub(crate) const MAX_RETRY_DELAY: Duration = Duration::from_secs(11 * 60 * 60); #[derive(Debug, Clone)] pub struct WorkerConfig { pub concurrency: usize, + /// Maximum deliveries handed to the worker but not yet settled. Late fill results may be carried separately. pub batch: usize, pub wait: Duration, pub visibility: Duration, @@ -78,7 +78,7 @@ impl Default for WorkerConfig { fn default() -> Self { Self { concurrency: 16, - batch: MAX_BATCH, + batch: 16, wait: MAX_WAIT, visibility: Duration::from_secs(60), auto_heartbeat: false, @@ -96,8 +96,10 @@ impl WorkerConfig { "concurrency must be 1..=Semaphore::MAX_PERMITS", )); } - if !(1..=MAX_BATCH).contains(&self.batch) { - return Err(Error::InvalidConfig("batch must be 1..=10")); + if !(1..=Semaphore::MAX_PERMITS).contains(&self.batch) { + return Err(Error::InvalidConfig( + "batch must be 1..=Semaphore::MAX_PERMITS", + )); } if self.wait.subsec_nanos() != 0 || self.wait.is_zero() || self.wait > MAX_WAIT { return Err(Error::InvalidConfig( diff --git a/rust/crates/queue/src/worker.rs b/rust/crates/queue/src/worker.rs index 48fcf9497..c98a5370b 100644 --- a/rust/crates/queue/src/worker.rs +++ b/rust/crates/queue/src/worker.rs @@ -1,10 +1,12 @@ mod process; +mod pull; mod settlement; +mod wait; use std::{future::Future, pin::Pin, sync::Arc, time::Duration}; use serde_json::value::RawValue; -use storage_queue_transport::{Received, Transport}; +use storage_queue_transport::Transport; use tokio::{ sync::Semaphore, task::{JoinHandle, JoinSet}, @@ -15,9 +17,9 @@ use tracing::warn; use crate::{BoxError, Context, Disposition, Error, Job, WorkerConfig}; use process::handle; +use pull::Puller; type BoxFuture = Pin + Send>>; -const RECEIVE_RETRY_DELAY: Duration = Duration::from_secs(1); trait Handler: Send + Sync { fn start( @@ -114,22 +116,62 @@ impl Worker { dead_letter: self.dead_letter, jobs: CancellationToken::new(), }); - let permits = Arc::new(Semaphore::new(shared.config.concurrency)); + let permits = Arc::new(Semaphore::new(shared.config.batch)); + let slots = Arc::new(Semaphore::new(shared.config.concurrency)); let mut tasks = JoinSet::new(); + let mut puller = Puller::new(shared.clone(), permits); - while let Some(messages) = receive(&shared, &permits, &shutdown).await { + while let Some(messages) = puller.receive(&shutdown).await { for (message, permit, received_at, receive_started) in messages { let shared = shared.clone(); + let slots = slots.clone(); tasks.spawn(async move { - handle(&shared, message, received_at, receive_started).await; + let release = + match wait::acquire(&shared, &message, received_at, receive_started, slots) + .await + { + wait::Outcome::Acquired(_slot, received_at) => { + handle(&shared, message, received_at, receive_started).await; + None + } + wait::Outcome::Release(deadline) => Some((message.receipt, deadline)), + wait::Outcome::Lost => None, + }; drop(permit); + release }); } while tasks.try_join_next().is_some() {} } shared.jobs.cancel(); - let drain = async { while tasks.join_next().await.is_some() {} }; + let drain = async { + puller.close().await; + while let Some(result) = tasks.join_next().await { + let mut releases = Vec::new(); + if let Ok(Some(release)) = result { + releases.push(release); + } + while let Some(result) = tasks.try_join_next() { + if let Ok(Some(release)) = result { + releases.push(release); + } + } + let now = Instant::now(); + let safety = Duration::from_secs(1).min(shared.config.visibility / 10); + let receipts: Vec<&str> = releases + .iter() + .filter(|(_, deadline)| now < *deadline - safety) + .map(|(receipt, _)| receipt.as_str()) + .collect(); + if !receipts.is_empty() { + let _ = shared + .transport + .extend_batch(&receipts, Duration::ZERO) + .await; + } + } + }; if time::timeout(grace, drain).await.is_err() { warn!("shutdown grace elapsed, aborting in-flight jobs"); } @@ -137,55 +179,3 @@ impl Worker { Ok(()) } } - -async fn receive( - shared: &Shared, - permits: &Arc, - shutdown: &CancellationToken, -) -> Option< - Vec<( - Received, - tokio::sync::OwnedSemaphorePermit, - Instant, - Instant, - )>, -> { - let config = &shared.config; - let first = tokio::select! { - biased; - _ = shutdown.cancelled() => return None, - permit = permits.clone().acquire_owned() => permit.expect("semaphore is never closed"), - }; - let mut held = vec![first]; - while held.len() < config.batch { - match permits.clone().try_acquire_owned() { - Ok(permit) => held.push(permit), - Err(_) => break, - } - } - let receive_started = Instant::now(); - let result = tokio::select! { - biased; - _ = shutdown.cancelled() => return None, - result = shared.transport.receive(held.len(), config.wait, config.visibility) => result, - }; - match result { - Ok(messages) => { - let received_at = Instant::now(); - Some( - messages - .into_iter() - .zip(held) - .map(|(message, permit)| (message, permit, received_at, receive_started)) - .collect(), - ) - } - Err(e) => { - warn!(error = ?e, "receive failed"); - tokio::select! { - _ = shutdown.cancelled() => None, - _ = time::sleep(RECEIVE_RETRY_DELAY) => Some(Vec::new()), - } - } - } -} diff --git a/rust/crates/queue/src/worker/pull.rs b/rust/crates/queue/src/worker/pull.rs new file mode 100644 index 000000000..94d9ec506 --- /dev/null +++ b/rust/crates/queue/src/worker/pull.rs @@ -0,0 +1,273 @@ +use std::{ + collections::{HashMap, VecDeque}, + sync::Arc, + time::Duration, +}; + +use storage_queue_transport::{Received, Transport}; +use tokio::{ + sync::{OwnedSemaphorePermit, Semaphore}, + task::JoinSet, + time::{self, Instant}, +}; +use tokio_util::sync::CancellationToken; +use tracing::warn; + +use super::Shared; + +const RECEIVE_BATCH: usize = 10; +const FILL_TIMEOUT: Duration = Duration::from_secs(1); +const RECEIVE_RETRY_DELAY: Duration = Duration::from_secs(1); + +type Buffered = (Received, Instant, Instant); +type Delivery = (Received, OwnedSemaphorePermit, Instant, Instant); +type Fill = (u64, Vec); + +pub(super) struct Puller { + shared: Arc>, + permits: Arc, + pending: JoinSet, + carried: VecDeque, + generation: u64, +} + +impl Puller { + pub(super) fn new(shared: Arc>, permits: Arc) -> Self { + Self { + shared, + permits, + pending: JoinSet::new(), + carried: VecDeque::new(), + generation: 0, + } + } + + fn collect_ready(&mut self) { + while let Some(result) = self.pending.try_join_next() { + if let Ok((_, messages)) = result { + self.carried.extend(messages); + } + } + } + + async fn once( + shared: &Shared, + max: usize, + wait: Duration, + ) -> Result, storage_queue_transport::Error> { + let started = Instant::now(); + let messages = shared + .transport + .receive(max, wait, shared.config.visibility) + .await?; + let received = Instant::now(); + Ok(messages + .into_iter() + .map(|message| (message, received, started)) + .collect()) + } + + pub(super) async fn receive(&mut self, shutdown: &CancellationToken) -> Option> { + self.collect_ready(); + let first = loop { + tokio::select! { + biased; + _ = shutdown.cancelled() => return None, + result = self.pending.join_next(), if !self.pending.is_empty() && self.carried.is_empty() => { + if let Some(Ok((_, messages))) = result { self.carried.extend(messages); } + } + permit = self.permits.clone().acquire_owned() => break permit.expect("semaphore is never closed"), + } + }; + let mut permits = vec![first]; + while permits.len() < self.shared.config.batch { + match self.permits.clone().try_acquire_owned() { + Ok(permit) => permits.push(permit), + Err(_) => break, + } + } + self.collect_ready(); + let mut taken = Vec::new(); + while !permits.is_empty() { + let Some((message, received, started)) = self.carried.pop_front() else { + break; + }; + taken.push((message, permits.pop().expect("checked"), received, started)); + } + let visibility = self.shared.config.visibility; + let safety = Duration::from_secs(1).min(visibility / 10); + let now = Instant::now(); + taken.retain(|(_, _, received, _)| now < *received + visibility - safety); + deduplicate(&mut taken); + let mut renewed = Vec::new(); + if !taken.is_empty() { + let requested = Instant::now(); + let receipts: Vec<&str> = taken + .iter() + .map(|(message, _, _, _)| message.receipt.as_str()) + .collect(); + let result = tokio::select! { + biased; + _ = shutdown.cancelled() => return None, + result = self.shared.transport.extend_batch(&receipts, visibility) => result, + }; + if let Ok(accepted) = result + && accepted.len() == taken.len() + && Instant::now() < requested + visibility + { + renewed.extend(taken.into_iter().zip(accepted).filter_map( + |((message, permit, _, started), accepted)| { + accepted.then_some((message, permit, requested, started)) + }, + )); + } + } + self.pull(renewed, permits, shutdown).await + } + + async fn pull( + &mut self, + mut received: Vec, + mut permits: Vec, + shutdown: &CancellationToken, + ) -> Option> { + let config = &self.shared.config; + while received.len() + permits.len() < config.batch { + match self.permits.clone().try_acquire_owned() { + Ok(permit) => permits.push(permit), + Err(_) => break, + } + } + if permits.is_empty() { + deduplicate(&mut received); + return Some(received); + } + let initial: Vec<_> = permits.drain(..permits.len().min(RECEIVE_BATCH)).collect(); + let wait = if received.is_empty() { + config.wait + } else { + Duration::ZERO + }; + let first = tokio::select! { + biased; + _ = shutdown.cancelled() => { + self.park_deliveries(received); + return None; + }, + result = Self::once(&self.shared, initial.len(), wait) => result, + }; + let first = match first { + Ok(first) => first, + Err(error) => { + warn!(?error, "receive failed"); + drop(received); + tokio::select! { + _ = shutdown.cancelled() => return None, + _ = time::sleep(RECEIVE_RETRY_DELAY) => return Some(Vec::new()), + } + } + }; + let full = first.len() == RECEIVE_BATCH; + received.extend( + first + .into_iter() + .zip(initial) + .map(|((message, received, started), permit)| (message, permit, received, started)), + ); + if !full || permits.is_empty() { + deduplicate(&mut received); + return Some(received); + } + + self.generation = self.generation.wrapping_add(1); + let generation = self.generation; + let mut remaining = permits.len().div_ceil(RECEIVE_BATCH); + let mut to_request = permits.len(); + while to_request > 0 { + let max = to_request.min(RECEIVE_BATCH); + to_request -= max; + let shared = self.shared.clone(); + self.pending.spawn(async move { + let messages = Self::once(&shared, max, Duration::ZERO) + .await + .unwrap_or_default(); + (generation, messages) + }); + } + let deadline = Instant::now() + FILL_TIMEOUT; + loop { + tokio::select! { + biased; + _ = shutdown.cancelled() => { + self.park_deliveries(received); + return None; + }, + _ = time::sleep_until(deadline) => break, + result = self.pending.join_next(), if !self.pending.is_empty() => { + match result { + Some(Ok((id, messages))) if id == generation => { + remaining -= 1; + let count = messages.len().min(permits.len()); + received.extend(messages.into_iter().zip(permits.drain(..count)).map(|((message, received, started), permit)| (message, permit, received, started))); + } + Some(Ok((_, messages))) => self.carried.extend(messages), + _ => {} + } + if remaining == 0 { break; } + } + else => break, + } + } + deduplicate(&mut received); + Some(received) + } + + fn park_deliveries(&mut self, deliveries: Vec) { + self.carried.extend( + deliveries + .into_iter() + .map(|(message, _, received, started)| (message, received, started)), + ); + } + + pub(super) async fn close(&mut self) { + self.collect_ready(); + self.pending.abort_all(); + let visibility = self.shared.config.visibility; + let safety = Duration::from_secs(1).min(visibility / 10); + let receipts: Vec<&str> = self + .carried + .iter() + .filter(|(_, received, _)| Instant::now() < *received + visibility - safety) + .map(|(message, _, _)| message.receipt.as_str()) + .collect(); + if !receipts.is_empty() { + let _ = self + .shared + .transport + .extend_batch(&receipts, Duration::ZERO) + .await; + } + self.carried.clear(); + } +} + +fn deduplicate(messages: &mut Vec) { + let mut latest = HashMap::new(); + for (index, (message, _, _, _)) in messages.iter().enumerate() { + let current = latest + .entry(message.id.clone()) + .or_insert((message.receive_count, index)); + if message.receive_count > current.0 { + *current = (message.receive_count, index); + } + } + let mut index = 0; + messages.retain(|(message, _, _, _)| { + let keep = latest + .get(&message.id) + .is_some_and(|(_, retained)| *retained == index); + index += 1; + keep + }); +} diff --git a/rust/crates/queue/src/worker/wait.rs b/rust/crates/queue/src/worker/wait.rs new file mode 100644 index 000000000..cfdfcebc1 --- /dev/null +++ b/rust/crates/queue/src/worker/wait.rs @@ -0,0 +1,68 @@ +use std::{future::Future, pin::Pin, sync::Arc, time::Duration}; + +use storage_queue_transport::{Received, Transport}; +use tokio::{ + sync::{OwnedSemaphorePermit, Semaphore}, + time::{self, Instant}, +}; +use tracing::warn; + +use super::{Shared, settlement::remaining_window}; + +type Heartbeat<'a> = ( + Instant, + Pin> + Send + 'a>>, +); + +pub(super) enum Outcome { + Acquired(OwnedSemaphorePermit, Instant), + Release(Instant), + Lost, +} + +pub(super) async fn acquire( + shared: &Shared, + message: &Received, + mut received_at: Instant, + receive_started: Instant, + slots: Arc, +) -> Outcome { + let visibility = shared.config.visibility; + let half = visibility / 2; + let mut deadline = received_at + visibility; + let mut next_beat = received_at + half; + let mut heartbeat: Option> = None; + loop { + tokio::select! { + biased; + _ = time::sleep_until(deadline) => return Outcome::Lost, + result = async { heartbeat.as_mut().expect("guarded").1.as_mut().await }, if heartbeat.is_some() => { + let (started, _) = heartbeat.take().expect("guarded"); + match result { + Ok(()) => { + deadline = started + visibility; + received_at = started; + next_beat = started + half; + } + Err(storage_queue_transport::Error::StaleReceipt) => return Outcome::Lost, + Err(error) => { + if shared.jobs.is_cancelled() { return Outcome::Lost; } + warn!(?error, "heartbeat for waiting job failed"); + next_beat = Instant::now() + Duration::from_secs(1).min(half); + } + } + } + _ = shared.jobs.cancelled(), if heartbeat.is_none() => { + return Outcome::Release(deadline); + } + permit = slots.clone().acquire_owned(), if heartbeat.is_none() => { + return Outcome::Acquired(permit.expect("semaphore is never closed"), received_at); + } + _ = time::sleep_until(next_beat), if shared.config.auto_heartbeat && heartbeat.is_none() => { + let started = Instant::now(); + if remaining_window(receive_started, started) < visibility { return Outcome::Lost; } + heartbeat = Some((started, Box::pin(shared.transport.extend(&message.receipt, visibility)))); + } + } + } +} diff --git a/rust/crates/queue/tests/pull.rs b/rust/crates/queue/tests/pull.rs new file mode 100644 index 000000000..e90ebc735 --- /dev/null +++ b/rust/crates/queue/tests/pull.rs @@ -0,0 +1,532 @@ +use std::{ + sync::{Arc, Mutex}, + time::Duration, +}; + +use serde_json::json; +use storage_queue::{BoxError, Context, Disposition, Job, Worker, WorkerConfig}; +use storage_queue_transport::{Error, Outgoing, Received, Transport}; +use tokio::{ + sync::{Semaphore, mpsc, oneshot}, + task::JoinHandle, + time, +}; +use tokio_util::sync::CancellationToken; + +struct Request { + max: usize, + wait: Duration, + reply: oneshot::Sender, Error>>, +} + +struct Scripted { + requests: mpsc::UnboundedSender, + changes: Mutex, Duration)>>, + accept_renewal: bool, +} + +impl Transport for Scripted { + async fn send(&self, _: &[Outgoing]) -> Result<(), Error> { + unreachable!() + } + + async fn receive( + &self, + max: usize, + wait: Duration, + _: Duration, + ) -> Result, Error> { + let (reply, result) = oneshot::channel(); + self.requests.send(Request { max, wait, reply }).unwrap(); + result + .await + .unwrap_or_else(|_| Err(Error::InvalidResponse("receive failed"))) + } + + async fn extend(&self, receipt: &str, visibility: Duration) -> Result<(), Error> { + self.changes + .lock() + .unwrap() + .push((vec![receipt.to_owned()], visibility)); + Ok(()) + } + + async fn extend_batch( + &self, + receipts: &[&str], + visibility: Duration, + ) -> Result, Error> { + self.changes.lock().unwrap().push(( + receipts.iter().map(|r| (*r).to_owned()).collect(), + visibility, + )); + Ok(vec![self.accept_renewal; receipts.len()]) + } + + async fn delete(&self, _: &[&str]) -> Result<(), Error> { + Ok(()) + } +} + +struct Handler { + started: Arc>>, + finish: Arc, +} + +impl Job for Handler { + const NAME: &'static str = "pull-test"; + type Payload = String; + async fn run(&self, ctx: Context, payload: String) -> Result { + self.started + .lock() + .unwrap() + .push((payload, ctx.receive_count)); + tokio::select! { + permit = self.finish.acquire() => permit.unwrap().forget(), + _ = ctx.cancel.cancelled() => {} + } + Ok(Disposition::Done) + } +} + +fn messages(start: usize, count: usize) -> Vec { + (start..start + count) + .map(|n| Received { + id: format!("id-{n}"), + receipt: format!("receipt-{n}"), + body: json!(format!("id-{n}")).to_string(), + receive_count: 1, + group_id: None, + attributes: Default::default(), + }) + .collect() +} + +struct Harness { + requests: mpsc::UnboundedReceiver, + transport: Arc, + started: Arc>>, + finish: Arc, + shutdown: CancellationToken, + worker: JoinHandle>, +} + +fn start(batch: usize, concurrency: usize, accept_renewal: bool) -> Harness { + start_with( + WorkerConfig { + batch, + concurrency, + ..WorkerConfig::default() + }, + accept_renewal, + ) +} + +fn start_with(config: WorkerConfig, accept_renewal: bool) -> Harness { + let (tx, requests) = mpsc::unbounded_channel(); + let transport = Arc::new(Scripted { + requests: tx, + changes: Mutex::new(Vec::new()), + accept_renewal, + }); + let started = Arc::new(Mutex::new(Vec::new())); + let finish = Arc::new(Semaphore::new(0)); + let mut worker = Worker::new(transport.clone(), config).unwrap(); + worker.register(Handler { + started: started.clone(), + finish: finish.clone(), + }); + let shutdown = CancellationToken::new(); + let task = tokio::spawn(worker.run(shutdown.clone())); + Harness { + requests, + transport, + started, + finish, + shutdown, + worker: task, + } +} + +async fn spin_until(mut condition: impl FnMut() -> bool) { + for _ in 0..10_000 { + if condition() { + return; + } + tokio::task::yield_now().await; + } + panic!("condition not reached"); +} + +async fn stop(harness: Harness) { + harness.shutdown.cancel(); + harness.worker.await.unwrap().unwrap(); +} + +#[tokio::test(start_paused = true)] +async fn fills_in_parallel_then_renews_late_results_without_exceeding_concurrency() { + let mut h = start(40, 20, true); + let first = h.requests.recv().await.unwrap(); + assert_eq!((first.max, first.wait), (10, Duration::from_secs(20))); + first.reply.send(Ok(messages(0, 10))).unwrap(); + let mut fills = Vec::new(); + for _ in 0..3 { + let request = h.requests.recv().await.unwrap(); + assert_eq!((request.max, request.wait), (10, Duration::ZERO)); + fills.push(request); + } + fills.remove(0).reply.send(Ok(messages(10, 10))).unwrap(); + for _ in 0..10 { + tokio::task::yield_now().await; + } + time::advance(Duration::from_millis(999)).await; + assert!(h.started.lock().unwrap().is_empty()); + time::advance(Duration::from_millis(1)).await; + spin_until(|| h.started.lock().unwrap().len() == 20).await; + let next = h.requests.recv().await.unwrap(); + assert_eq!(next.wait, Duration::from_secs(20)); + fills.remove(0).reply.send(Ok(messages(20, 10))).unwrap(); + for _ in 0..10 { + tokio::task::yield_now().await; + } + next.reply.send(Ok(Vec::new())).unwrap(); + spin_until(|| { + h.transport + .changes + .lock() + .unwrap() + .iter() + .any(|(r, v)| r.len() == 10 && *v == Duration::from_secs(60)) + }) + .await; + assert_eq!(h.started.lock().unwrap().len(), 20); + let fill_carried = h.requests.recv().await.unwrap(); + assert_eq!(fill_carried.wait, Duration::ZERO); + fill_carried.reply.send(Ok(Vec::new())).unwrap(); + h.finish.add_permits(10); + spin_until(|| h.started.lock().unwrap().len() == 30).await; + stop(h).await; +} + +#[tokio::test(start_paused = true)] +async fn duplicate_ids_in_a_pull_use_the_latest_delivery() { + let mut h = start(20, 20, true); + h.requests + .recv() + .await + .unwrap() + .reply + .send(Ok(messages(0, 10))) + .unwrap(); + let fill = h.requests.recv().await.unwrap(); + let mut more = messages(10, 9); + let mut duplicate = messages(0, 1).pop().unwrap(); + duplicate.receive_count = 2; + duplicate.receipt = "new-receipt".into(); + more.push(duplicate); + fill.reply.send(Ok(more)).unwrap(); + spin_until(|| h.started.lock().unwrap().len() == 19).await; + let started = h.started.lock().unwrap().clone(); + assert_eq!(started.iter().filter(|(id, _)| id == "id-0").count(), 1); + assert!(started.contains(&("id-0".to_owned(), 2))); + stop(h).await; +} + +#[tokio::test(start_paused = true)] +async fn partial_first_receive_does_not_fan_out() { + let mut h = start(40, 40, true); + h.requests + .recv() + .await + .unwrap() + .reply + .send(Ok(messages(0, 5))) + .unwrap(); + let next = h.requests.recv().await.unwrap(); + assert_eq!((next.max, next.wait), (10, Duration::from_secs(20))); + spin_until(|| h.started.lock().unwrap().len() == 5).await; + stop(h).await; + assert!(next.reply.is_closed()); +} + +#[tokio::test(start_paused = true)] +async fn failed_renewal_drops_late_messages() { + let mut h = start(20, 10, false); + h.requests + .recv() + .await + .unwrap() + .reply + .send(Ok(messages(0, 10))) + .unwrap(); + let fill = h.requests.recv().await.unwrap(); + time::advance(Duration::from_secs(1)).await; + spin_until(|| h.started.lock().unwrap().len() == 10).await; + let next = h.requests.recv().await.unwrap(); + fill.reply.send(Ok(messages(10, 10))).unwrap(); + for _ in 0..10 { + tokio::task::yield_now().await; + } + next.reply.send(Ok(Vec::new())).unwrap(); + spin_until(|| !h.transport.changes.lock().unwrap().is_empty()).await; + assert_eq!(h.started.lock().unwrap().len(), 10); + stop(h).await; +} + +#[tokio::test(start_paused = true)] +async fn queued_jobs_heartbeat_until_a_handler_slot_is_available() { + let (tx, mut requests) = mpsc::unbounded_channel(); + let transport = Arc::new(Scripted { + requests: tx, + changes: Mutex::new(Vec::new()), + accept_renewal: true, + }); + let started = Arc::new(Mutex::new(Vec::new())); + let finish = Arc::new(Semaphore::new(0)); + let mut worker = Worker::new( + transport.clone(), + WorkerConfig { + batch: 2, + concurrency: 1, + visibility: Duration::from_secs(4), + auto_heartbeat: true, + execution_timeout: Some(Duration::from_secs(30)), + ..WorkerConfig::default() + }, + ) + .unwrap(); + worker.register(Handler { + started: started.clone(), + finish: finish.clone(), + }); + let shutdown = CancellationToken::new(); + let task = tokio::spawn(worker.run(shutdown.clone())); + requests + .recv() + .await + .unwrap() + .reply + .send(Ok(messages(0, 2))) + .unwrap(); + spin_until(|| started.lock().unwrap().len() == 1).await; + time::advance(Duration::from_secs(2)).await; + spin_until(|| { + transport + .changes + .lock() + .unwrap() + .iter() + .filter(|(_, d)| *d == Duration::from_secs(4)) + .count() + >= 2 + }) + .await; + finish.add_permits(1); + spin_until(|| started.lock().unwrap().len() == 2).await; + shutdown.cancel(); + task.await.unwrap().unwrap(); +} + +#[tokio::test(start_paused = true)] +async fn expired_queued_job_does_not_start() { + let (tx, mut requests) = mpsc::unbounded_channel(); + let transport = Arc::new(Scripted { + requests: tx, + changes: Mutex::new(Vec::new()), + accept_renewal: true, + }); + let started = Arc::new(Mutex::new(Vec::new())); + let finish = Arc::new(Semaphore::new(0)); + let mut worker = Worker::new( + transport, + WorkerConfig { + batch: 2, + concurrency: 1, + visibility: Duration::from_secs(2), + ..WorkerConfig::default() + }, + ) + .unwrap(); + worker.register(Handler { + started: started.clone(), + finish, + }); + let shutdown = CancellationToken::new(); + let task = tokio::spawn(worker.run(shutdown.clone())); + requests + .recv() + .await + .unwrap() + .reply + .send(Ok(messages(0, 2))) + .unwrap(); + spin_until(|| started.lock().unwrap().len() == 1).await; + time::advance(Duration::from_secs(2)).await; + for _ in 0..20 { + tokio::task::yield_now().await; + } + assert_eq!(started.lock().unwrap().len(), 1); + shutdown.cancel(); + task.await.unwrap().unwrap(); +} + +#[tokio::test(start_paused = true)] +async fn shutdown_cancels_late_receives_and_releases_waiting_jobs() { + let mut h = start(20, 1, true); + h.requests + .recv() + .await + .unwrap() + .reply + .send(Ok(messages(0, 10))) + .unwrap(); + let fill = h.requests.recv().await.unwrap(); + time::advance(Duration::from_secs(1)).await; + spin_until(|| h.started.lock().unwrap().len() == 1).await; + h.shutdown.cancel(); + h.worker.await.unwrap().unwrap(); + assert!(fill.reply.is_closed()); + assert_eq!( + h.transport + .changes + .lock() + .unwrap() + .iter() + .filter(|(_, d)| d.is_zero()) + .map(|(receipts, _)| receipts.len()) + .sum::(), + 9 + ); +} + +#[tokio::test(start_paused = true)] +async fn shutdown_during_fill_releases_the_received_batch() { + let mut h = start(20, 20, true); + h.requests + .recv() + .await + .unwrap() + .reply + .send(Ok(messages(0, 10))) + .unwrap(); + let fill = h.requests.recv().await.unwrap(); + let transport = h.transport.clone(); + h.shutdown.cancel(); + h.worker.await.unwrap().unwrap(); + assert!(fill.reply.is_closed()); + let changes = transport.changes.lock().unwrap(); + assert!( + changes + .iter() + .any(|(receipts, duration)| receipts.len() == 10 && duration.is_zero()) + ); +} + +#[tokio::test(start_paused = true)] +async fn five_hundred_message_prefetch_fans_out_in_requests_of_ten() { + let mut h = start(500, 1, true); + h.requests + .recv() + .await + .unwrap() + .reply + .send(Ok(messages(0, 10))) + .unwrap(); + for i in 0..49 { + let fill = h.requests.recv().await.unwrap(); + assert_eq!((fill.max, fill.wait), (10, Duration::ZERO)); + fill.reply.send(Ok(messages(10 + i * 10, 10))).unwrap(); + } + spin_until(|| h.started.lock().unwrap().len() == 1).await; + assert!(h.requests.try_recv().is_err()); + stop(h).await; +} + +#[tokio::test(start_paused = true)] +async fn shutdown_releases_late_messages_parked_during_a_new_long_poll() { + let mut h = start(20, 10, true); + h.requests + .recv() + .await + .unwrap() + .reply + .send(Ok(messages(0, 10))) + .unwrap(); + let late = h.requests.recv().await.unwrap(); + time::advance(Duration::from_secs(1)).await; + spin_until(|| h.started.lock().unwrap().len() == 10).await; + let next = h.requests.recv().await.unwrap(); + late.reply.send(Ok(messages(10, 10))).unwrap(); + for _ in 0..20 { + tokio::task::yield_now().await; + } + h.shutdown.cancel(); + h.worker.await.unwrap().unwrap(); + assert!(next.reply.is_closed()); + assert!( + h.transport + .changes + .lock() + .unwrap() + .iter() + .any(|(receipts, delay)| receipts.len() == 10 && delay.is_zero()) + ); +} + +#[tokio::test(start_paused = true)] +async fn expired_carried_message_is_not_renewed_or_dispatched() { + let mut h = start_with( + WorkerConfig { + batch: 20, + concurrency: 10, + visibility: Duration::from_secs(2), + ..WorkerConfig::default() + }, + true, + ); + h.requests + .recv() + .await + .unwrap() + .reply + .send(Ok(messages(0, 10))) + .unwrap(); + let fill = h.requests.recv().await.unwrap(); + time::advance(Duration::from_secs(1)).await; + spin_until(|| h.started.lock().unwrap().len() == 10).await; + let next = h.requests.recv().await.unwrap(); + fill.reply.send(Ok(messages(10, 10))).unwrap(); + for _ in 0..10 { + tokio::task::yield_now().await; + } + time::advance(Duration::from_secs(2)).await; + next.reply.send(Ok(Vec::new())).unwrap(); + let following = h.requests.recv().await.unwrap(); + assert_eq!(following.wait, Duration::from_secs(20)); + assert!(h.transport.changes.lock().unwrap().is_empty()); + assert_eq!(h.started.lock().unwrap().len(), 10); + stop(h).await; +} + +#[tokio::test(start_paused = true)] +async fn failed_fill_does_not_delay_other_results() { + let mut h = start(30, 30, true); + let started = time::Instant::now(); + h.requests + .recv() + .await + .unwrap() + .reply + .send(Ok(messages(0, 10))) + .unwrap(); + let first_fill = h.requests.recv().await.unwrap(); + let second_fill = h.requests.recv().await.unwrap(); + first_fill + .reply + .send(Err(Error::InvalidResponse("failed fill"))) + .unwrap(); + second_fill.reply.send(Ok(messages(10, 10))).unwrap(); + spin_until(|| h.started.lock().unwrap().len() == 20).await; + assert!(started.elapsed() < Duration::from_secs(1)); + stop(h).await; +} diff --git a/rust/crates/queue/tests/sqs.rs b/rust/crates/queue/tests/sqs.rs index 7ac11c7fb..82bad4c21 100644 --- a/rust/crates/queue/tests/sqs.rs +++ b/rust/crates/queue/tests/sqs.rs @@ -181,3 +181,47 @@ async fn processes_jobs_and_drains_queue() { .is_empty() ); } + +#[tokio::test] +#[ignore = "requires an SQS-compatible endpoint"] +async fn fills_prefetch_across_multiple_sqs_receives() { + let queue = Arc::new(queue().await); + let done = Arc::new(Mutex::new(Vec::new())); + let jobs: Vec<_> = (0..25) + .map(|id| { + encode::(&Payload { + tenant: Tenant { + reference: "tenant-1".into(), + host: "localhost".into(), + }, + id, + retry_once: false, + }) + .unwrap() + }) + .collect(); + queue.send(&jobs).await.unwrap(); + let mut worker = Worker::new( + queue, + WorkerConfig { + batch: 40, + concurrency: 3, + wait: Duration::from_secs(1), + ..WorkerConfig::default() + }, + ) + .unwrap(); + worker.register(Echo(done.clone())); + let shutdown = CancellationToken::new(); + let handle = tokio::spawn(worker.run(shutdown.clone())); + let deadline = Instant::now() + Duration::from_secs(15); + while done.lock().unwrap().len() < jobs.len() { + assert!(Instant::now() < deadline, "jobs did not complete"); + sleep(Duration::from_millis(50)).await; + } + shutdown.cancel(); + handle.await.unwrap().unwrap(); + let mut ids: Vec<_> = done.lock().unwrap().iter().map(|(id, _)| *id).collect(); + ids.sort_unstable(); + assert_eq!(ids, (0..25).collect::>()); +} diff --git a/rust/crates/queue/tests/worker.rs b/rust/crates/queue/tests/worker.rs index 63720b1e6..3d72c8096 100644 --- a/rust/crates/queue/tests/worker.rs +++ b/rust/crates/queue/tests/worker.rs @@ -256,6 +256,7 @@ impl Transport for Fake { m.count += 1; m.visible_at = now + visibility; Received { + id: m.receipt.clone(), receipt: m.receipt.clone(), body: m.body.clone(), receive_count: m.count, @@ -870,6 +871,7 @@ async fn timeout_does_not_settle_after_lease_loss() { let (stats, fake, worker) = setup(WorkerConfig { auto_heartbeat: true, concurrency: 1, + batch: 1, visibility: Duration::from_secs(2), execution_timeout: Some(Duration::from_millis(500)), shutdown_grace: Duration::from_secs(3), @@ -1187,9 +1189,10 @@ async fn concurrency_is_bounded() { let mut first = true; for call in fake.calls() { if let Call::Receive { max, running } = call { - assert!(max + running <= 3, "max {max} with {running} running"); + assert!(max <= 10, "receive requested {max} messages"); + assert!(running <= 3, "{running} handlers were running"); if std::mem::take(&mut first) { - assert_eq!(max, 3); + assert_eq!(max, 10); } } } @@ -1243,7 +1246,10 @@ fn invalid_config_is_rejected() { ..d() }, WorkerConfig { batch: 0, ..d() }, - WorkerConfig { batch: 11, ..d() }, + WorkerConfig { + batch: Semaphore::MAX_PERMITS + 1, + ..d() + }, WorkerConfig { wait: Duration::ZERO, ..d()