laravel-rust-queue 0.1.0

Internal crate of Laravel for Rust: jobs, the queue drivers, the worker, batches, and chains. Depend on `laravel-rust` instead
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
//! The `sqs` driver: jobs in Amazon SQS queues.
//!
//! A job's attempt count is its message's receive count, which SQS keeps only approximately. A
//! release hides the message for its delay, at most until 12 hours after the message was
//! received, so the job keeps its place and its count.
//!
//! Each message wraps its payload in an envelope that carries the job's message group. SQS
//! delays a message by at most 15 minutes, so the driver sends a longer delay in hops of up to
//! 15 minutes, and the envelope carries the time the dispatch delay ends.
//!
//! A FIFO queue, whose name ends in `.fifo`, runs each message group's jobs one at a time, in
//! order. SQS can't delay a new message on a FIFO queue, and a delayed job would hold up its
//! whole group, so dispatching a delayed job to a FIFO queue fails.
//!
//! An SQS message holds at most 1 MiB. With overflow enabled, the driver stores a larger payload
//! in a cache store, and the message carries the payload's cache key.

use std::collections::HashMap;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant};

use aws_sdk_sqs::Client;
use aws_sdk_sqs::config::{BehaviorVersion, Credentials, Region};
use aws_sdk_sqs::error::{DisplayErrorContext, ProvideErrorMetadata};
use aws_sdk_sqs::types::{MessageSystemAttributeName, QueueAttributeName, SendMessageBatchRequestEntry};
use aws_smithy_http_client::tls::{Provider, rustls_provider::CryptoMode};
use serde::{Deserialize, Serialize};

use super::payload::unix_now;
use super::{Driver, LEASE, QueueSizes, Reservation, ReservedJob};
use crate::cache::Repository;
use crate::config::queue::{SqsOverflow, SqsQueue};
use crate::{Error, Result};

/// The longest SQS delays a message, in seconds.
const MAX_DELAY: i64 = 15 * 60;

/// The longest SQS hides a received message, in seconds, counted from when it was received.
const MAX_VISIBILITY: i64 = 12 * 60 * 60;

/// The largest message body SQS accepts, in bytes.
const MAX_MESSAGE: usize = 1024 * 1024;

/// The most messages SQS takes in one batch.
const MAX_BATCH: usize = 10;

const OVERFLOW_PREFIX: &str = "laravel:sqs-payloads:";

const OVERFLOW_TTL: Duration = Duration::from_secs(14 * 24 * 60 * 60);

const VISIBILITY: i32 = LEASE.as_secs() as i32;

pub(crate) struct Sqs {
    client: Client,
    prefix: String,
    suffix: String,
    overflow: Option<SqsOverflow>,
    urls: Mutex<HashMap<String, String>>,
}

impl Sqs {
    pub(crate) async fn connect(config: &SqsQueue) -> Self {
        let mut loader = aws_config::defaults(BehaviorVersion::latest()).http_client(
            aws_smithy_http_client::Builder::new()
                .tls_provider(Provider::Rustls(CryptoMode::Ring))
                .build_https(),
        );
        if let Some(region) = &config.region {
            loader = loader.region(Region::new(region.clone()));
        }
        if let Some(endpoint) = &config.endpoint {
            loader = loader.endpoint_url(endpoint);
        }
        if let Some(credentials) = &config.credentials {
            loader = loader.credentials_provider(Credentials::new(
                &credentials.key,
                &credentials.secret,
                credentials.token.clone(),
                None,
                "laravel",
            ));
        }

        Self {
            client: Client::new(&loader.load().await),
            prefix: config.prefix.trim_end_matches('/').to_owned(),
            suffix: config.suffix.clone(),
            overflow: config.overflow.clone(),
            urls: Mutex::default(),
        }
    }

    pub(crate) async fn url(&self, queue: &str) -> Result<String> {
        if queue.starts_with("https://") || queue.starts_with("http://") {
            return Ok(queue.to_owned());
        }
        let name = match queue.strip_suffix(".fifo") {
            Some(name) => format!("{name}{}.fifo", self.suffix),
            None => format!("{queue}{}", self.suffix),
        };
        if !self.prefix.is_empty() {
            return Ok(format!("{}/{name}", self.prefix));
        }
        if let Some(url) = self.urls.lock().unwrap_or_else(PoisonError::into_inner).get(&name) {
            return Ok(url.clone());
        }

        let output = self
            .client
            .get_queue_url()
            .queue_name(&name)
            .send()
            .await
            .map_err(|error| failure("find the URL of", &name, &error))?;
        let url = output
            .queue_url
            .ok_or_else(|| crate::error::fail(format!("SQS has no URL for the queue `{name}`")))?;
        self.urls
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(name, url.clone());

        Ok(url)
    }

    /// Send a job's envelope to a queue, available after `delay`, in hops of at most 15 minutes.
    /// A FIFO queue's message gets `deduplication_id` or a unique one, and can't be delayed.
    pub(crate) async fn send(
        &self,
        url: &str,
        envelope: Envelope,
        delay: Duration,
        deduplication_id: Option<&str>,
    ) -> Result<()> {
        let message = self.message(url, envelope, delay, deduplication_id).await?;

        self.client
            .send_message()
            .queue_url(url)
            .message_body(message.body)
            .set_delay_seconds(message.delay_seconds)
            .set_message_group_id(message.group)
            .set_message_deduplication_id(message.deduplication_id)
            .send()
            .await
            .map_err(|error| failure("send a job to", url, &error))?;

        Ok(())
    }

    /// Send jobs' envelopes to a queue in order, in batches of up to 10 messages and 1 MiB.
    /// Sending stops at the first batch SQS doesn't take in full, so no job arrives ahead of one
    /// that wasn't sent.
    async fn send_batches(&self, url: &str, messages: Vec<Message>) -> Result<()> {
        let mut messages = messages.into_iter().peekable();
        while messages.peek().is_some() {
            let mut entries = Vec::new();
            let mut size = 0;
            while let Some(message) = messages.next_if(|message| {
                entries.len() < MAX_BATCH && (entries.is_empty() || size + message.body.len() <= MAX_MESSAGE)
            }) {
                size += message.body.len();
                entries.push(
                    SendMessageBatchRequestEntry::builder()
                        .id(entries.len().to_string())
                        .message_body(message.body)
                        .set_delay_seconds(message.delay_seconds)
                        .set_message_group_id(message.group)
                        .set_message_deduplication_id(message.deduplication_id)
                        .build()
                        .map_err(|error| crate::error::fail(format!("a job couldn't be sent to SQS: {error}")))?,
                );
            }

            let output = self
                .client
                .send_message_batch()
                .queue_url(url)
                .set_entries(Some(entries))
                .send()
                .await
                .map_err(|error| failure("send jobs to", url, &error))?;
            if let Some(failed) = output.failed.first() {
                return Err(crate::error::fail(format!(
                    "SQS refused {} of the jobs sent to the queue `{url}`: {} {}",
                    output.failed.len(),
                    failed.code,
                    failed.message.as_deref().unwrap_or_default()
                )));
            }
        }

        Ok(())
    }

    async fn message(
        &self,
        url: &str,
        mut envelope: Envelope,
        delay: Duration,
        deduplication_id: Option<&str>,
    ) -> Result<Message> {
        let fifo = is_fifo(url);
        let seconds = seconds(delay);
        if fifo && seconds > 0 {
            return Err(crate::error::fail(format!(
                "the SQS FIFO queue `{url}` can't delay jobs, since a delayed job would hold up every job behind it in its group; dispatch delayed jobs to a standard queue"
            )));
        }
        envelope.available_at = if seconds > MAX_DELAY {
            unix_now().saturating_add(seconds)
        } else {
            0
        };
        let mut body = encode(&envelope)?;
        if body.len() > MAX_MESSAGE || self.overflow.as_ref().is_some_and(|overflow| overflow.always) {
            body = self.overflow(envelope.clone(), body.len()).await?;
        }
        let group = match &envelope.group {
            Some(group) => Some(group.clone()),
            None => fifo.then(|| url.rsplit('/').next().unwrap_or(url).to_owned()),
        };
        let deduplication_id = fifo.then(|| match deduplication_id {
            Some(id) => id.to_owned(),
            None => crate::str::uuid7().to_string(),
        });

        Ok(Message {
            body,
            // Without a delay, the queue's own delay applies...
            delay_seconds: (seconds > 0).then(|| i32::try_from(seconds.min(MAX_DELAY)).unwrap_or(0)),
            group,
            deduplication_id,
        })
    }

    async fn sizes(&self, queue: &str) -> Result<QueueSizes> {
        let url = self.url(queue).await?;
        let attributes = self
            .client
            .get_queue_attributes()
            .queue_url(&url)
            .attribute_names(QueueAttributeName::ApproximateNumberOfMessages)
            .attribute_names(QueueAttributeName::ApproximateNumberOfMessagesDelayed)
            .attribute_names(QueueAttributeName::ApproximateNumberOfMessagesNotVisible)
            .send()
            .await
            .map_err(|error| failure("count the jobs on", &url, &error))?
            .attributes
            .unwrap_or_default();
        let count = |name: QueueAttributeName| {
            attributes
                .get(&name)
                .and_then(|count| count.parse::<u64>().ok())
                .unwrap_or_default()
        };

        Ok(QueueSizes {
            pending: count(QueueAttributeName::ApproximateNumberOfMessages),
            delayed: count(QueueAttributeName::ApproximateNumberOfMessagesDelayed),
            reserved: count(QueueAttributeName::ApproximateNumberOfMessagesNotVisible),
            oldest_pending: None,
            approximate: true,
        })
    }

    async fn overflow(&self, mut envelope: Envelope, size: usize) -> Result<String> {
        if envelope.cached {
            return encode(&envelope);
        }
        if self.overflow.is_none() {
            return Err(crate::error::fail(format!(
                "the job is {size} bytes, more than an SQS message holds; enable the connection's overflow to keep large payloads in the cache"
            )));
        }

        let key = format!("{OVERFLOW_PREFIX}{}", crate::str::uuid7());
        self.cache()?.put(&key, &envelope.payload, OVERFLOW_TTL).await?;
        envelope.payload = key;
        envelope.cached = true;

        encode(&envelope)
    }

    fn cache(&self) -> Result<Repository> {
        let manager = crate::cache::manager();
        match self.overflow.as_ref().and_then(|overflow| overflow.store.as_deref()) {
            Some(store) => manager.store(store),
            None => manager.default_store(),
        }
    }

    pub(crate) async fn open(&self, body: String, received: u32) -> Result<Opened> {
        let envelope = Envelope::read(body);
        let now = unix_now();
        if envelope.available_at > now {
            let wait = Duration::from_secs(envelope.available_at.saturating_sub(now).cast_unsigned());
            return Ok(Opened::Early { envelope, wait });
        }

        let payload = if envelope.cached {
            let key = envelope.payload;
            self.cache()?.get::<String>(&key).await?.unwrap_or_else(|| {
                tracing::warn!(target: "laravel::queue", key, "A queued job's payload is missing from the cache");
                String::new()
            })
        } else {
            envelope.payload
        };

        Ok(Opened::Due(Reserved {
            payload,
            attempts: received.max(1),
            received: Instant::now(),
        }))
    }

    async fn receive(self: &Arc<Self>, queue: &str) -> Result<Option<SqsJob>> {
        let url = self.url(queue).await?;
        loop {
            let output = self
                .client
                .receive_message()
                .queue_url(&url)
                .max_number_of_messages(1)
                .visibility_timeout(VISIBILITY)
                .message_system_attribute_names(MessageSystemAttributeName::ApproximateReceiveCount)
                .send()
                .await
                .map_err(|error| failure("receive a job from", &url, &error))?;
            let Some(message) = output.messages.and_then(|messages| messages.into_iter().next()) else {
                return Ok(None);
            };
            let receipt = message.receipt_handle.unwrap_or_default();
            let received = message
                .attributes
                .as_ref()
                .and_then(|attributes| attributes.get(&MessageSystemAttributeName::ApproximateReceiveCount))
                .and_then(|count| count.parse().ok())
                .unwrap_or(1);

            match self.open(message.body.unwrap_or_default(), received).await? {
                Opened::Due(reserved) => {
                    return Ok(Some(SqsJob {
                        sqs: Arc::clone(self),
                        url,
                        receipt,
                        queue: queue.to_owned(),
                        reserved,
                    }));
                }
                Opened::Early { envelope, wait } => {
                    // A spawned hop finishes when the worker stops, so it can't send a copy and keep the message...
                    let (sqs, url) = (Arc::clone(self), url.clone());
                    crate::task::spawn(async move {
                        sqs.send(&url, envelope, wait, None).await?;
                        sqs.delete(&url, &receipt).await
                    })
                    .await??;
                }
            }
        }
    }

    async fn hide(&self, url: &str, receipt: &str, seconds: i32) -> Result<bool> {
        match self
            .client
            .change_message_visibility()
            .queue_url(url)
            .receipt_handle(receipt)
            .visibility_timeout(seconds)
            .send()
            .await
        {
            Ok(_) => Ok(true),
            Err(error) if is_lost(&error) => Ok(false),
            Err(error) => Err(failure("change a job's visibility on", url, &error)),
        }
    }

    async fn delete(&self, url: &str, receipt: &str) -> Result<bool> {
        match self
            .client
            .delete_message()
            .queue_url(url)
            .receipt_handle(receipt)
            .send()
            .await
        {
            Ok(_) => Ok(true),
            Err(error) if is_lost(&error) => Ok(false),
            Err(error) => Err(failure("delete a job from", url, &error)),
        }
    }
}

pub(crate) struct SqsDriver(pub(crate) Arc<Sqs>);

impl Driver for SqsDriver {
    type Job = SqsJob;

    async fn push(&self, queue: &str, payload: String, delay: Duration) -> Result<()> {
        let url = self.0.url(queue).await?;
        let (envelope, deduplication_id) = Envelope::grouped(payload);

        self.0.send(&url, envelope, delay, deduplication_id.as_deref()).await
    }

    async fn bulk(&self, queue: &str, payloads: Vec<String>) -> Result<()> {
        let url = self.0.url(queue).await?;
        let mut messages = Vec::with_capacity(payloads.len());
        for payload in payloads {
            let (envelope, deduplication_id) = Envelope::grouped(payload);
            messages.push(
                self.0
                    .message(&url, envelope, Duration::ZERO, deduplication_id.as_deref())
                    .await?,
            );
        }

        self.0.send_batches(&url, messages).await
    }

    async fn sizes(&self, queue: &str) -> Result<Option<QueueSizes>> {
        self.0.sizes(queue).await.map(Some)
    }

    async fn reserve(&self, queues: &[String]) -> Result<Option<SqsJob>> {
        for queue in queues {
            if let Some(job) = self.0.receive(queue).await? {
                return Ok(Some(job));
            }
        }

        Ok(None)
    }

    async fn clear(&self, queue: &str) -> Result<u64> {
        let count = self.0.sizes(queue).await?.total();
        let url = self.0.url(queue).await?;
        self.0
            .client
            .purge_queue()
            .queue_url(&url)
            .send()
            .await
            .map_err(|error| failure("purge", &url, &error))?;

        Ok(count)
    }
}

#[derive(Deserialize, Default)]
struct Grouping {
    #[serde(default)]
    group: Option<String>,
    #[serde(default)]
    deduplication_id: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct Envelope {
    pub(crate) payload: String,
    #[serde(default, skip_serializing_if = "is_zero")]
    pub(crate) cached: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) group: Option<String>,
    #[serde(default, skip_serializing_if = "is_zero")]
    pub(crate) available_at: i64,
}

impl Envelope {
    pub(crate) const fn new(payload: String) -> Self {
        Self {
            payload,
            cached: false,
            group: None,
            available_at: 0,
        }
    }

    fn grouped(payload: String) -> (Self, Option<String>) {
        let grouping = serde_json::from_str::<Grouping>(&payload).unwrap_or_default();
        let envelope = Self {
            group: grouping.group,
            ..Self::new(payload)
        };

        (envelope, grouping.deduplication_id)
    }

    pub(crate) fn read(body: String) -> Self {
        serde_json::from_str(&body).unwrap_or_else(|_| Self::new(body))
    }
}

fn is_zero<T: Default + PartialEq>(value: &T) -> bool {
    *value == T::default()
}

struct Message {
    body: String,
    delay_seconds: Option<i32>,
    group: Option<String>,
    deduplication_id: Option<String>,
}

pub(crate) enum Opened {
    Due(Reserved),
    Early { envelope: Envelope, wait: Duration },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Reserved {
    pub(crate) payload: String,
    pub(crate) attempts: u32,
    pub(crate) received: Instant,
}

pub(crate) struct SqsJob {
    sqs: Arc<Sqs>,
    url: String,
    receipt: String,
    queue: String,
    reserved: Reserved,
}

impl SqsJob {
    pub(crate) const fn reserved(&self) -> &Reserved {
        &self.reserved
    }
}

impl ReservedJob for SqsJob {
    fn queue(&self) -> &str {
        &self.queue
    }

    fn payload(&self) -> &str {
        &self.reserved.payload
    }

    fn attempts(&self) -> u32 {
        self.reserved.attempts
    }

    async fn renew(&self) -> Result<Reservation> {
        self.sqs
            .hide(&self.url, &self.receipt, VISIBILITY)
            .await
            .map(Reservation::held_if)
    }

    async fn delete(&self) -> Result<Reservation> {
        self.sqs
            .delete(&self.url, &self.receipt)
            .await
            .map(Reservation::held_if)
    }

    /// Hide the message for the delay, so the job keeps its place, and a FIFO queue's group
    /// waits for it.
    async fn release(&self, delay: Duration) -> Result<Reservation> {
        self.sqs
            .hide(
                &self.url,
                &self.receipt,
                released_for(delay, self.reserved.received.elapsed()),
            )
            .await
            .map(Reservation::held_if)
    }
}

pub(crate) fn is_fifo(url: &str) -> bool {
    url.ends_with(".fifo")
}

/// How long to hide a released message, in whole seconds: its delay, up to the end of the 12
/// hours SQS lets a message stay hidden after it was received, `held` ago.
pub(crate) fn released_for(delay: Duration, held: Duration) -> i32 {
    // A second more than `held` covers the time the receipt took to reach the worker...
    let left = (MAX_VISIBILITY - seconds(held) - 1).max(0);
    let seconds = seconds(delay);
    if seconds > left {
        tracing::warn!(
            target: "laravel::queue",
            seconds,
            "SQS hides a released job for at most 12 hours after it was received, so it's available sooner than its delay"
        );
    }

    i32::try_from(seconds.min(left)).unwrap_or(0)
}

fn encode(envelope: &Envelope) -> Result<String> {
    serde_json::to_string(envelope)
        .map_err(|error| crate::error::fail(format!("a job couldn't be encoded for SQS: {error}")))
}

/// Whether SQS rejected a receipt because the message's reservation lapsed or it was deleted.
fn is_lost<E: ProvideErrorMetadata>(error: &E) -> bool {
    match error.code() {
        Some("ReceiptHandleIsInvalid" | "MessageNotInflight" | "AWS.SimpleQueueService.MessageNotInflight") => true,
        Some("InvalidParameterValue") => error.message().is_some_and(|message| message.contains("ReceiptHandle")),
        _ => false,
    }
}

fn failure<E>(action: &str, queue: &str, error: &E) -> Error
where
    E: ProvideErrorMetadata + std::error::Error + 'static,
{
    if matches!(
        error.code(),
        Some("AWS.SimpleQueueService.NonExistentQueue" | "QueueDoesNotExist")
    ) {
        return crate::error::fail(format!("the SQS queue `{queue}` doesn't exist"));
    }

    crate::error::fail(format!(
        "couldn't {action} the SQS queue `{queue}`: {}",
        DisplayErrorContext(error)
    ))
}

fn seconds(delay: Duration) -> i64 {
    let seconds = delay.as_secs().saturating_add(u64::from(delay.subsec_nanos() > 0));

    i64::try_from(seconds).unwrap_or(i64::MAX)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn releases_wait_at_most_until_twelve_hours_after_the_receipt() {
        let held = Duration::from_millis(9500);

        assert_eq!(released_for(Duration::ZERO, held), 0);
        assert_eq!(released_for(Duration::from_millis(1500), held), 2);
        assert_eq!(released_for(Duration::from_secs(13 * 60 * 60), held), 12 * 60 * 60 - 11);
        assert_eq!(
            released_for(Duration::from_secs(60), Duration::from_secs(13 * 60 * 60)),
            0
        );
    }

    #[test]
    fn bodies_that_arent_envelopes_are_payloads() {
        let envelope = Envelope::new(r#"{"job":"app::Job"}"#.into());
        let body = serde_json::to_string(&envelope).unwrap();

        assert_eq!(body, r#"{"payload":"{\"job\":\"app::Job\"}"}"#);
        assert_eq!(Envelope::read(body), envelope);
        assert_eq!(Envelope::read(r#"{"job":"app::Job"}"#.into()), envelope);
    }
}