shove 0.10.0

Async tasks via pubsub on steroids. Comes with built-in support for complex queue configurations, audit logs, autoscaling consumer groups and more.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
use aws_sdk_sqs::types::QueueAttributeName;
use std::collections::HashMap;
use tokio::sync::RwLock;
use tracing::{debug, info};

use crate::backends::sns::client::SnsClient;
use crate::error::{Result, ShoveError};
use crate::topology::QueueTopology;

/// Default SQS maxReceiveCount for redrive policies.
/// Messages that exceed this receive count are moved to the DLQ.
#[cfg(feature = "aws-sns-sqs")]
const DEFAULT_MAX_RECEIVE_COUNT: u32 = 10;

/// Registry mapping queue names to SNS topic ARNs.
///
/// Populated by the topology declarer or pre-configured ARNs.
/// Shared between the declarer and publisher via `Arc`.
pub struct TopicRegistry {
    arns: RwLock<HashMap<String, String>>,
}

impl Default for TopicRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl TopicRegistry {
    pub fn new() -> Self {
        Self {
            arns: RwLock::new(HashMap::new()),
        }
    }

    pub fn with_overrides(overrides: HashMap<String, String>) -> Self {
        Self {
            arns: RwLock::new(overrides),
        }
    }

    pub async fn get(&self, queue_name: &str) -> Option<String> {
        self.arns.read().await.get(queue_name).cloned()
    }

    pub async fn insert(&self, queue_name: String, arn: String) {
        self.arns.write().await.insert(queue_name, arn);
    }
}

/// Registry mapping queue names to SQS queue URLs.
#[cfg(feature = "aws-sns-sqs")]
pub struct QueueRegistry {
    urls: RwLock<HashMap<String, String>>,
}

#[cfg(feature = "aws-sns-sqs")]
impl Default for QueueRegistry {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "aws-sns-sqs")]
impl QueueRegistry {
    pub fn new() -> Self {
        Self {
            urls: RwLock::new(HashMap::new()),
        }
    }

    pub async fn get(&self, queue_name: &str) -> Option<String> {
        self.urls.read().await.get(queue_name).cloned()
    }

    pub async fn insert(&self, queue_name: String, url: String) {
        self.urls.write().await.insert(queue_name, url);
    }
}

/// Returns the SNS topic name for a given queue topology.
///
/// Sequenced topics get a `.fifo` suffix to create FIFO SNS topics.
fn sns_topic_name(topology: &QueueTopology) -> String {
    if topology.sequencing().is_some() {
        format!("{}.fifo", topology.queue())
    } else {
        topology.queue().to_string()
    }
}

/// Declares SNS topics for a topic's topology.
///
/// Creates standard SNS topics for unsequenced topics and FIFO SNS topics
/// (with content-based deduplication) for sequenced topics. All create
/// operations are idempotent — safe to call on every startup.
///
/// Registry state is read from the underlying [`SnsClient`], so every
/// declarer, publisher, and consumer group built from the same client
/// share a single source of truth for topic ARNs and queue URLs.
pub struct SnsTopologyDeclarer {
    client: SnsClient,
}

impl SnsTopologyDeclarer {
    pub fn new(client: SnsClient) -> Self {
        Self { client }
    }

    fn topic_registry(&self) -> &TopicRegistry {
        self.client.topic_registry()
    }

    #[cfg(feature = "aws-sns-sqs")]
    fn queue_registry(&self) -> &QueueRegistry {
        self.client.queue_registry()
    }

    async fn declare_standard(&self, topology: &QueueTopology) -> Result<()> {
        let topic_name = sns_topic_name(topology);

        debug!(topic_name, "declaring standard SNS topic");

        let result = self
            .client
            .inner()
            .create_topic()
            .name(&topic_name)
            .send()
            .await
            .map_err(|e| {
                ShoveError::Topology(format!("failed to create SNS topic '{topic_name}': {e}"))
            })?;

        let arn = result
            .topic_arn()
            .ok_or_else(|| {
                ShoveError::Topology(format!(
                    "SNS topic '{topic_name}' created but no ARN returned"
                ))
            })?
            .to_string();

        info!(topic_name, arn, "standard SNS topic declared");
        self.topic_registry()
            .insert(topology.queue().to_string(), arn)
            .await;

        Ok(())
    }

    async fn declare_fifo(&self, topology: &QueueTopology) -> Result<()> {
        let topic_name = sns_topic_name(topology);

        debug!(topic_name, "declaring FIFO SNS topic");

        let result = self
            .client
            .inner()
            .create_topic()
            .name(&topic_name)
            .attributes("FifoTopic", "true")
            .attributes("ContentBasedDeduplication", "true")
            .send()
            .await
            .map_err(|e| {
                ShoveError::Topology(format!(
                    "failed to create FIFO SNS topic '{topic_name}': {e}"
                ))
            })?;

        let arn = result
            .topic_arn()
            .ok_or_else(|| {
                ShoveError::Topology(format!(
                    "FIFO SNS topic '{topic_name}' created but no ARN returned"
                ))
            })?
            .to_string();

        info!(topic_name, arn, "FIFO SNS topic declared");
        self.topic_registry()
            .insert(topology.queue().to_string(), arn)
            .await;

        Ok(())
    }

    /// Create an SQS queue and return its (url, arn).
    #[cfg(feature = "aws-sns-sqs")]
    async fn create_sqs_queue(
        &self,
        name: &str,
        fifo: bool,
        dlq_arn: Option<&str>,
        max_receive_count: u32,
    ) -> Result<(String, String)> {
        let mut req = self.client.sqs().create_queue().queue_name(name);

        if fifo {
            req = req
                .attributes(QueueAttributeName::FifoQueue, "true")
                .attributes(QueueAttributeName::ContentBasedDeduplication, "true");
        }

        if let Some(arn) = dlq_arn {
            let redrive = serde_json::json!({
                "deadLetterTargetArn": arn,
                "maxReceiveCount": max_receive_count,
            })
            .to_string();
            req = req.attributes(QueueAttributeName::RedrivePolicy, redrive);
        }

        let result = req.send().await.map_err(|e| {
            ShoveError::Topology(format!("failed to create SQS queue '{name}': {e}"))
        })?;

        let url = result
            .queue_url()
            .ok_or_else(|| {
                ShoveError::Topology(format!("SQS queue '{name}' created but no URL returned"))
            })?
            .to_string();

        // Fetch the ARN
        let attrs = self
            .client
            .sqs()
            .get_queue_attributes()
            .queue_url(&url)
            .attribute_names(QueueAttributeName::QueueArn)
            .send()
            .await
            .map_err(|e| {
                ShoveError::Topology(format!(
                    "failed to get attributes for SQS queue '{name}': {e}"
                ))
            })?;

        let arn = attrs
            .attributes()
            .and_then(|m| m.get(&QueueAttributeName::QueueArn))
            .ok_or_else(|| {
                ShoveError::Topology(format!("SQS queue '{name}' has no ARN attribute"))
            })?
            .clone();

        info!(name, url, arn, "SQS queue declared");
        Ok((url, arn))
    }

    /// Set the SQS queue policy to allow SNS delivery and subscribe it to the topic.
    #[cfg(feature = "aws-sns-sqs")]
    async fn subscribe_sqs_to_sns(
        &self,
        topic_arn: &str,
        queue_arn: &str,
        queue_url: &str,
        filter_policy: Option<String>,
    ) -> Result<()> {
        // Allow SNS to send messages to the SQS queue
        let policy = serde_json::json!({
            "Version": "2012-10-17",
            "Statement": [{
                "Effect": "Allow",
                "Principal": { "Service": "sns.amazonaws.com" },
                "Action": "sqs:SendMessage",
                "Resource": queue_arn,
                "Condition": {
                    "ArnEquals": { "aws:SourceArn": topic_arn }
                }
            }]
        })
        .to_string();

        self.client
            .sqs()
            .set_queue_attributes()
            .queue_url(queue_url)
            .attributes(QueueAttributeName::Policy, policy)
            .send()
            .await
            .map_err(|e| {
                ShoveError::Topology(format!(
                    "failed to set SQS queue policy for '{queue_url}': {e}"
                ))
            })?;

        // Subscribe SQS to SNS
        let mut sub_req = self
            .client
            .inner()
            .subscribe()
            .topic_arn(topic_arn)
            .protocol("sqs")
            .endpoint(queue_arn)
            .attributes("RawMessageDelivery", "true");

        if let Some(fp) = filter_policy {
            sub_req = sub_req.attributes("FilterPolicy", fp);
        }

        sub_req.send().await.map_err(|e| {
            ShoveError::Topology(format!(
                "failed to subscribe SQS queue '{queue_arn}' to SNS topic '{topic_arn}': {e}"
            ))
        })?;

        Ok(())
    }

    /// Declare a standard (unsequenced) SQS queue and subscribe it to the SNS topic.
    #[cfg(feature = "aws-sns-sqs")]
    async fn declare_sqs_unsequenced(
        &self,
        topology: &QueueTopology,
        topic_arn: &str,
    ) -> Result<()> {
        let queue_name = topology.queue();

        // Create DLQ first if requested
        let dlq_arn = if let Some(dlq_name) = topology.dlq() {
            let (dlq_url, arn) = self.create_sqs_queue(dlq_name, false, None, 0).await?;
            self.queue_registry()
                .insert(dlq_name.to_string(), dlq_url)
                .await;
            Some(arn)
        } else {
            None
        };

        // Create the main queue with optional redrive to DLQ
        let (url, arn) = self
            .create_sqs_queue(
                queue_name,
                false,
                dlq_arn.as_deref(),
                DEFAULT_MAX_RECEIVE_COUNT,
            )
            .await?;

        // Subscribe to SNS
        self.subscribe_sqs_to_sns(topic_arn, &arn, &url, None)
            .await?;

        self.queue_registry()
            .insert(queue_name.to_string(), url)
            .await;

        Ok(())
    }

    /// Declare FIFO shard queues and subscribe each to the SNS topic.
    #[cfg(feature = "aws-sns-sqs")]
    async fn declare_sqs_sequenced(&self, topology: &QueueTopology, topic_arn: &str) -> Result<()> {
        let queue_name = topology.queue();
        let shards = topology
            .sequencing()
            .map(|s| s.routing_shards())
            .unwrap_or(8);

        // Derive the DLQ registry key (without .fifo suffix for registry lookups)
        let dlq_registry_key = topology
            .dlq()
            .unwrap_or(&format!("{queue_name}-dlq"))
            .to_string();

        // Create FIFO DLQ (actual AWS name must have .fifo suffix)
        let dlq_aws_name = format!("{dlq_registry_key}.fifo");
        let (dlq_url, dlq_arn) = self.create_sqs_queue(&dlq_aws_name, true, None, 0).await?;

        // Register DLQ URL using the key without .fifo
        self.queue_registry()
            .insert(dlq_registry_key, dlq_url)
            .await;

        // Create N FIFO shard queues
        for i in 0..shards {
            let shard_registry_key = format!("{queue_name}-seq-{i}");
            let shard_aws_name = format!("{shard_registry_key}.fifo");
            let (url, arn) = self
                .create_sqs_queue(
                    &shard_aws_name,
                    true,
                    Some(&dlq_arn),
                    DEFAULT_MAX_RECEIVE_COUNT,
                )
                .await?;

            // Filter policy: only receive messages for this shard
            let filter = serde_json::json!({ "shard": [i.to_string()] }).to_string();

            self.subscribe_sqs_to_sns(topic_arn, &arn, &url, Some(filter))
                .await?;

            self.queue_registry().insert(shard_registry_key, url).await;
        }

        Ok(())
    }
}

impl SnsTopologyDeclarer {
    pub async fn declare(&self, topology: &QueueTopology) -> Result<()> {
        // If the registry already has an ARN for this queue (pre-configured),
        // validate it exists and skip creation.
        if let Some(arn) = self.topic_registry().get(topology.queue()).await {
            debug!(
                queue = topology.queue(),
                arn, "using pre-configured SNS topic ARN"
            );

            self.client
                .inner()
                .get_topic_attributes()
                .topic_arn(&arn)
                .send()
                .await
                .map_err(|e| {
                    ShoveError::Topology(format!(
                        "pre-configured SNS topic ARN '{arn}' is invalid: {e}"
                    ))
                })?;

            // Declare SQS queues if not yet registered (idempotent).
            #[cfg(feature = "aws-sns-sqs")]
            if self.queue_registry().get(topology.queue()).await.is_none() {
                if topology.sequencing().is_some() {
                    self.declare_sqs_sequenced(topology, &arn).await?;
                } else {
                    self.declare_sqs_unsequenced(topology, &arn).await?;
                }
            }

            return Ok(());
        }

        if topology.sequencing().is_some() {
            self.declare_fifo(topology).await?;
        } else {
            self.declare_standard(topology).await?;
        }

        // Declare SQS queues if not yet registered (idempotent).
        #[cfg(feature = "aws-sns-sqs")]
        if self.queue_registry().get(topology.queue()).await.is_none() {
            let topic_arn = self
                .topic_registry()
                .get(topology.queue())
                .await
                .expect("topic ARN must be in registry after declare");

            if topology.sequencing().is_some() {
                self.declare_sqs_sequenced(topology, &topic_arn).await?;
            } else {
                self.declare_sqs_unsequenced(topology, &topic_arn).await?;
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::SequenceFailure;
    use crate::topology::TopologyBuilder;
    use std::time::Duration;

    #[test]
    fn sns_topic_name_standard() {
        let topology = TopologyBuilder::new("order-settlement").build();
        assert_eq!(sns_topic_name(&topology), "order-settlement");
    }

    #[test]
    fn sns_topic_name_fifo() {
        let topology = TopologyBuilder::new("order-settlement")
            .sequenced(SequenceFailure::Skip)
            .hold_queue(Duration::from_secs(5))
            .dlq()
            .build();
        assert_eq!(sns_topic_name(&topology), "order-settlement.fifo");
    }

    #[tokio::test]
    async fn registry_insert_and_get() {
        let registry = TopicRegistry::new();
        registry
            .insert("orders".into(), "arn:aws:sns:us-east-1:123:orders".into())
            .await;
        let arn = registry.get("orders").await;
        assert_eq!(arn, Some("arn:aws:sns:us-east-1:123:orders".to_string()));
    }

    #[tokio::test]
    async fn registry_get_missing() {
        let registry = TopicRegistry::new();
        assert_eq!(registry.get("nonexistent").await, None);
    }

    #[tokio::test]
    async fn registry_with_overrides() {
        let mut overrides = HashMap::new();
        overrides.insert("orders".into(), "arn:aws:sns:us-east-1:123:orders".into());
        let registry = TopicRegistry::with_overrides(overrides);
        assert_eq!(
            registry.get("orders").await,
            Some("arn:aws:sns:us-east-1:123:orders".to_string())
        );
    }

    #[tokio::test]
    async fn registry_insert_overwrites() {
        let registry = TopicRegistry::new();
        registry.insert("orders".into(), "arn:old".into()).await;
        registry.insert("orders".into(), "arn:new".into()).await;
        assert_eq!(registry.get("orders").await, Some("arn:new".to_string()));
    }

    #[cfg(feature = "aws-sns-sqs")]
    #[tokio::test]
    async fn queue_registry_insert_and_get() {
        let registry = QueueRegistry::new();
        registry
            .insert(
                "orders".into(),
                "https://sqs.us-east-1.amazonaws.com/123/orders".into(),
            )
            .await;
        let url = registry.get("orders").await;
        assert_eq!(
            url,
            Some("https://sqs.us-east-1.amazonaws.com/123/orders".to_string())
        );
    }

    #[cfg(feature = "aws-sns-sqs")]
    #[tokio::test]
    async fn queue_registry_get_missing() {
        let registry = QueueRegistry::new();
        assert_eq!(registry.get("nonexistent").await, None);
    }
}