Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
QUEUE_TEST_SQS_ENDPOINT: http://127.0.0.1:9324
40 changes: 40 additions & 0 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion rust/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
[workspace]
resolver = "3"
members = ["crates/queue"]
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"] }
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"
38 changes: 30 additions & 8 deletions rust/README.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,38 @@
# 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-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.

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
`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.

ElasticMQ (the SQS endpoint) is the `elasticmq` service in `.docker/docker-compose-infra.yml`.
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.

Start it from the repo root:
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.

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.

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/`:

QUEUE_TEST_SQS_ENDPOINT=http://127.0.0.1:9324 \
cargo test -- --ignored
12 changes: 12 additions & 0 deletions rust/crates/queue-transport/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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
164 changes: 164 additions & 0 deletions rust/crates/queue-transport/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
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<u8>),
}

#[derive(Debug, Clone)]
pub struct Outgoing {
pub body: String,
pub group_id: Option<String>,
pub attributes: HashMap<String, MessageAttribute>,
}

#[derive(Debug, Clone)]
pub struct Received {
pub id: String,
pub receipt: String,
pub body: String,
pub receive_count: u32,
pub group_id: Option<String>,
pub attributes: HashMap<String, MessageAttribute>,
}

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<Output = Result<(), Error>> + 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<Output = Result<Vec<Received>, 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<Output = Result<(), Error>> + Send;
/// Change visibility for several receipts, returning whether each was accepted.
fn extend_batch(
&self,
receipts: &[&str],
visibility: Duration,
) -> impl Future<Output = Result<Vec<bool>, 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.
fn delete(&self, receipts: &[&str]) -> impl Future<Output = Result<(), Error>> + 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<String>,
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<BatchOutcome>,
#[source]
pub source: Option<Box<dyn std::error::Error + Send + Sync>>,
}

#[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<String>,
message: Option<String>,
#[source]
source: Box<dyn std::error::Error + Send + Sync>,
},
#[error(transparent)]
Batch(#[from] BatchError),
#[error(transparent)]
Sqs(Box<dyn std::error::Error + Send + Sync>),
}

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(())
}
Loading
Loading