Skip to main content

relay_server/services/buffer/envelope_buffer/
mod.rs

1use std::cmp::Ordering;
2use std::collections::BTreeSet;
3use std::convert::Infallible;
4use std::error::Error;
5use std::mem;
6use std::ops::ControlFlow;
7use std::sync::Arc;
8use std::time::Duration;
9
10use chrono::{DateTime, Utc};
11use hashbrown::HashSet;
12use relay_base_schema::project::ProjectKey;
13use relay_config::ConfigSnapshot;
14use tokio::time::{Instant, timeout};
15
16use crate::envelope::Envelope;
17use crate::services::buffer::common::ProjectKeyPair;
18use crate::services::buffer::envelope_stack::EnvelopeStack;
19use crate::services::buffer::envelope_stack::sqlite::SqliteEnvelopeStackError;
20use crate::services::buffer::envelope_store::sqlite::SqliteEnvelopeStoreError;
21use crate::services::buffer::stack_provider::memory::MemoryStackProvider;
22use crate::services::buffer::stack_provider::sqlite::SqliteStackProvider;
23use crate::services::buffer::stack_provider::{StackCreationType, StackProvider};
24use crate::services::buffer::throttle::Throttle;
25use crate::statsd::{RelayDistributions, RelayGauges, RelayTimers};
26use crate::utils::MemoryChecker;
27
28/// Polymorphic envelope buffering interface.
29///
30/// The underlying buffer can either be disk-based or memory-based,
31/// depending on the given configuration.
32///
33/// NOTE: This is implemented as an enum because a trait object with async methods would not be
34/// object safe.
35#[derive(Debug)]
36#[allow(private_interfaces)]
37pub enum PolymorphicEnvelopeBuffer {
38    /// An enveloper buffer that uses in-memory envelopes stacks.
39    InMemory(EnvelopeBuffer<MemoryStackProvider>),
40    /// An enveloper buffer that uses sqlite envelopes stacks.
41    Sqlite(EnvelopeBuffer<SqliteStackProvider>),
42}
43
44impl PolymorphicEnvelopeBuffer {
45    /// Returns true if the implementation stores all envelopes in RAM.
46    pub fn is_memory(&self) -> bool {
47        match self {
48            Self::InMemory(_) => true,
49            Self::Sqlite(_) => false,
50        }
51    }
52
53    /// Creates either a memory-based or a disk-based envelope buffer,
54    /// depending on the given configuration.
55    pub async fn from_config(
56        partition_id: u8,
57        config: &ConfigSnapshot,
58        memory_checker: MemoryChecker,
59        throttle: Arc<Throttle>,
60    ) -> Result<Self, EnvelopeBufferError> {
61        let buffer = if config.spool_envelopes_path(partition_id).is_some() {
62            relay_log::trace!("PolymorphicEnvelopeBuffer: initializing sqlite envelope buffer");
63            let buffer =
64                EnvelopeBuffer::<SqliteStackProvider>::new(partition_id, config, throttle).await?;
65            Self::Sqlite(buffer)
66        } else {
67            relay_log::trace!("PolymorphicEnvelopeBuffer: initializing memory envelope buffer");
68            let buffer = EnvelopeBuffer::<MemoryStackProvider>::new(partition_id, memory_checker);
69            Self::InMemory(buffer)
70        };
71
72        Ok(buffer)
73    }
74
75    /// Initializes the envelope buffer.
76    pub async fn initialize(&mut self) {
77        match self {
78            PolymorphicEnvelopeBuffer::InMemory(buffer) => buffer.initialize().await,
79            PolymorphicEnvelopeBuffer::Sqlite(buffer) => buffer.initialize().await,
80        }
81    }
82
83    /// Adds an envelope to the buffer.
84    pub async fn push(&mut self, envelope: Box<Envelope>) -> Result<(), EnvelopeBufferError> {
85        relay_statsd::metric!(
86            distribution(RelayDistributions::BufferEnvelopeBodySize) = envelope
87                .items()
88                .map(|item| item.data().len())
89                .sum::<usize>()
90                as u64,
91            partition_id = self.partition_tag()
92        );
93
94        relay_statsd::metric!(
95            timer(RelayTimers::BufferPush),
96            partition_id = self.partition_tag(),
97            {
98                match self {
99                    Self::Sqlite(buffer) => buffer.push(envelope).await,
100                    Self::InMemory(buffer) => buffer.push(envelope).await,
101                }
102            }
103        )
104    }
105
106    /// Returns a reference to the next-in-line envelope.
107    pub async fn peek(&mut self) -> Result<Peek, EnvelopeBufferError> {
108        relay_statsd::metric!(
109            timer(RelayTimers::BufferPeek),
110            partition_id = self.partition_tag(),
111            {
112                match self {
113                    Self::Sqlite(buffer) => buffer.peek().await,
114                    Self::InMemory(buffer) => buffer.peek().await,
115                }
116            }
117        )
118    }
119
120    /// Pops the next-in-line envelope.
121    pub async fn pop(&mut self) -> Result<Option<Box<Envelope>>, EnvelopeBufferError> {
122        relay_statsd::metric!(
123            timer(RelayTimers::BufferPop),
124            partition_id = self.partition_tag(),
125            {
126                match self {
127                    Self::Sqlite(buffer) => buffer.pop().await,
128                    Self::InMemory(buffer) => buffer.pop().await,
129                }
130            }
131        )
132    }
133
134    /// Marks a project as ready or not ready.
135    ///
136    /// The buffer re-prioritizes its envelopes based on this information.
137    /// Returns `true` if at least one priority was changed.
138    pub fn mark_ready(&mut self, project: &ProjectKey, is_ready: bool) -> bool {
139        relay_log::trace!(
140            project_key = project.as_str(),
141            "buffer marked {}",
142            if is_ready { "ready" } else { "not ready" }
143        );
144        match self {
145            Self::Sqlite(buffer) => buffer.mark_ready(project, is_ready),
146            Self::InMemory(buffer) => buffer.mark_ready(project, is_ready),
147        }
148    }
149
150    /// Marks a stack as seen.
151    ///
152    /// Non-ready stacks are deprioritized when they are marked as seen, such that
153    /// the next call to `.peek()` will look at a different stack. This prevents
154    /// head-of-line blocking.
155    pub fn mark_seen(&mut self, project_key_pair: &ProjectKeyPair, next_fetch: Duration) {
156        match self {
157            Self::Sqlite(buffer) => buffer.mark_seen(project_key_pair, next_fetch),
158            Self::InMemory(buffer) => buffer.mark_seen(project_key_pair, next_fetch),
159        }
160    }
161
162    /// Returns `true` whether the buffer has capacity to accept new [`Envelope`]s.
163    pub fn has_capacity(&self) -> bool {
164        match self {
165            Self::Sqlite(buffer) => buffer.has_capacity(),
166            Self::InMemory(buffer) => buffer.has_capacity(),
167        }
168    }
169
170    /// Returns `true` if the buffer contains no envelopes, in memory or on disk.
171    pub fn is_empty(&self) -> bool {
172        match self {
173            Self::Sqlite(buffer) => buffer.is_empty(),
174            Self::InMemory(buffer) => buffer.is_empty(),
175        }
176    }
177
178    /// Returns the total number of envelopes that have been spooled since the startup. It does
179    /// not include the count that existed in a persistent spooler before.
180    pub fn item_count(&self) -> u64 {
181        match self {
182            Self::Sqlite(buffer) => buffer.tracked_count,
183            Self::InMemory(buffer) => buffer.tracked_count,
184        }
185    }
186
187    /// Returns the total number of bytes that the spooler storage uses or `None` if the number
188    /// cannot be reliably determined.
189    pub fn total_size(&self) -> Option<u64> {
190        match self {
191            Self::Sqlite(buffer) => buffer.stack_provider.total_size(),
192            Self::InMemory(buffer) => buffer.stack_provider.total_size(),
193        }
194    }
195
196    /// Shuts down the [`PolymorphicEnvelopeBuffer`].
197    ///
198    /// - In persistent disk mode, flush everything to disk and shut down.
199    /// - Otherwise, continue draining envelopes to the processor.
200    ///
201    /// Returns `Break` if all work has been done and the buffer service can stop.
202    pub async fn shutdown(&mut self) -> ControlFlow<()> {
203        match self {
204            Self::Sqlite(buffer) if !buffer.stack_provider.ephemeral() => {
205                buffer.flush().await;
206                ControlFlow::Break(())
207            }
208            Self::InMemory(_) | Self::Sqlite(_) => {
209                relay_log::trace!("shutdown procedure not needed");
210                ControlFlow::Continue(())
211            }
212        }
213    }
214
215    /// Returns the partition tag for this [`PolymorphicEnvelopeBuffer`].
216    fn partition_tag(&self) -> &str {
217        match self {
218            PolymorphicEnvelopeBuffer::InMemory(buffer) => &buffer.partition_tag,
219            PolymorphicEnvelopeBuffer::Sqlite(buffer) => &buffer.partition_tag,
220        }
221    }
222}
223
224/// Error that occurs while interacting with the envelope buffer.
225#[derive(Debug, thiserror::Error)]
226pub enum EnvelopeBufferError {
227    #[error("sqlite")]
228    SqliteStore(#[from] SqliteEnvelopeStoreError),
229
230    #[error("sqlite")]
231    SqliteStack(#[from] SqliteEnvelopeStackError),
232
233    #[error("failed to push envelope to the buffer")]
234    PushFailed,
235}
236
237impl From<Infallible> for EnvelopeBufferError {
238    fn from(value: Infallible) -> Self {
239        match value {}
240    }
241}
242
243/// An envelope buffer that holds an individual stack for each project/sampling project combination.
244///
245/// Envelope stacks are organized in a priority queue, and are re-prioritized every time an envelope
246/// is pushed, popped, or when a project becomes ready.
247#[derive(Debug)]
248struct EnvelopeBuffer<P: StackProvider> {
249    /// The central priority queue.
250    priority_queue: priority_queue::PriorityQueue<QueueItem<ProjectKeyPair, P::Stack>, Priority>,
251    /// A lookup table to find all stacks involving a project.
252    stacks_by_project: hashbrown::HashMap<ProjectKey, BTreeSet<ProjectKeyPair>>,
253    /// A provider of stacks that provides utilities to create stacks, check their capacity...
254    ///
255    /// This indirection is needed because different stack implementations might need different
256    /// initialization (e.g. a database connection).
257    stack_provider: P,
258    /// The total count of envelopes that the buffer is working with.
259    ///
260    /// Note that this count is not meant to be perfectly accurate since the initialization of the
261    /// count might not succeed if it takes more than a set timeout. For example, if we load the
262    /// count of all envelopes from disk, and it takes more than the time we set, we will mark the
263    /// initial count as 0 and just count incoming and outgoing envelopes from the buffer.
264    total_count: i64,
265    /// The total count of envelopes that the buffer is working with ignoring envelopes that
266    /// were previously stored on disk.
267    ///
268    /// On startup this will always be 0 and will only count incoming envelopes. If a reliable
269    /// count of currently buffered envelopes is required, prefer this over `total_count`
270    tracked_count: u64,
271    /// Whether the count initialization succeeded or not.
272    ///
273    /// This boolean is just used for tagging the metric that tracks the total count of envelopes
274    /// in the buffer.
275    total_count_initialized: bool,
276    /// The tag value of this partition which is used for reporting purposes.
277    partition_tag: String,
278}
279
280impl EnvelopeBuffer<MemoryStackProvider> {
281    /// Creates an empty memory-based buffer.
282    pub fn new(partition_id: u8, memory_checker: MemoryChecker) -> Self {
283        Self {
284            stacks_by_project: Default::default(),
285            priority_queue: Default::default(),
286            stack_provider: MemoryStackProvider::new(memory_checker),
287            total_count: 0,
288            tracked_count: 0,
289            total_count_initialized: false,
290            partition_tag: partition_id.to_string(),
291        }
292    }
293}
294
295#[allow(dead_code)]
296impl EnvelopeBuffer<SqliteStackProvider> {
297    /// Creates an empty sqlite-based buffer.
298    pub async fn new(
299        partition_id: u8,
300        config: &ConfigSnapshot,
301        throttle: Arc<Throttle>,
302    ) -> Result<Self, EnvelopeBufferError> {
303        Ok(Self {
304            stacks_by_project: Default::default(),
305            priority_queue: Default::default(),
306            stack_provider: SqliteStackProvider::new(partition_id, config, throttle).await?,
307            total_count: 0,
308            tracked_count: 0,
309            total_count_initialized: false,
310            partition_tag: partition_id.to_string(),
311        })
312    }
313}
314
315impl<P: StackProvider> EnvelopeBuffer<P>
316where
317    EnvelopeBufferError: From<<P::Stack as EnvelopeStack>::Error>,
318{
319    /// Initializes the [`EnvelopeBuffer`] given the initialization state from the
320    /// [`StackProvider`].
321    pub async fn initialize(&mut self) {
322        relay_statsd::metric!(
323            timer(RelayTimers::BufferInitialization),
324            partition_id = &self.partition_tag,
325            {
326                let initialization_state = self.stack_provider.initialize().await;
327                self.load_stacks(initialization_state.project_key_pairs)
328                    .await;
329                self.load_store_total_count().await;
330            }
331        );
332    }
333
334    /// Pushes an envelope to the appropriate envelope stack and re-prioritizes the stack.
335    ///
336    /// If the envelope stack does not exist, a new stack is pushed to the priority queue.
337    /// The priority of the stack is updated with the envelope's received_at time.
338    pub async fn push(&mut self, envelope: Box<Envelope>) -> Result<(), EnvelopeBufferError> {
339        let received_at = envelope.received_at();
340
341        let project_key_pair = ProjectKeyPair::from_envelope(&envelope);
342        if let Some((
343            QueueItem {
344                key: _,
345                value: stack,
346            },
347            _,
348        )) = self.priority_queue.get_mut(&project_key_pair)
349        {
350            stack.push(envelope).await?;
351        } else {
352            // Since we have initialization code that creates all the necessary stacks, we assume
353            // that any new stack that is added during the envelope buffer's lifecycle, is recreated.
354            self.push_stack(
355                StackCreationType::New,
356                ProjectKeyPair::from_envelope(&envelope),
357                Some(envelope),
358            )
359            .await?;
360        }
361        self.priority_queue
362            .change_priority_by(&project_key_pair, |prio| {
363                prio.received_at = received_at;
364            });
365
366        self.total_count += 1;
367        self.tracked_count += 1;
368        self.track_total_count();
369
370        Ok(())
371    }
372
373    /// Returns a reference to the next-in-line envelope, if one exists.
374    pub async fn peek(&mut self) -> Result<Peek, EnvelopeBufferError> {
375        let Some((
376            QueueItem {
377                key: project_key_pair,
378                value: stack,
379            },
380            Priority {
381                readiness,
382                next_project_fetch,
383                ..
384            },
385        )) = self.priority_queue.peek_mut()
386        else {
387            return Ok(Peek::Empty);
388        };
389
390        let ready = readiness.ready();
391
392        Ok(match (stack.peek().await?, ready) {
393            (None, _) => Peek::Empty,
394            (Some(last_received_at), true) => Peek::Ready {
395                project_key_pair: *project_key_pair,
396                last_received_at,
397            },
398            (Some(last_received_at), false) => Peek::NotReady {
399                project_key_pair: *project_key_pair,
400                next_project_fetch: *next_project_fetch,
401                last_received_at,
402            },
403        })
404    }
405
406    /// Returns the next-in-line envelope, if one exists.
407    ///
408    /// The priority of the envelope's stack is updated with the next envelope's received_at
409    /// time. If the stack is empty after popping, it is removed from the priority queue.
410    pub async fn pop(&mut self) -> Result<Option<Box<Envelope>>, EnvelopeBufferError> {
411        let Some((QueueItem { key, value: stack }, _)) = self.priority_queue.peek_mut() else {
412            return Ok(None);
413        };
414        let project_key_pair = *key;
415        let envelope = stack.pop().await?.expect("found an empty stack");
416
417        let last_received_at = stack.peek().await?;
418
419        match last_received_at {
420            None => {
421                self.pop_stack(project_key_pair);
422            }
423            Some(last_received_at) => {
424                self.priority_queue
425                    .change_priority_by(&project_key_pair, |prio| {
426                        prio.received_at = last_received_at;
427                    });
428            }
429        }
430
431        // We are fine with the count going negative, since it represents that more data was popped,
432        // than it was initially counted, meaning that we had a wrong total count from
433        // initialization.
434        self.total_count -= 1;
435        self.tracked_count = self.tracked_count.saturating_sub(1);
436        self.track_total_count();
437
438        Ok(Some(envelope))
439    }
440
441    /// Re-prioritizes all stacks that involve the given project key by setting it to "ready".
442    ///
443    /// Returns `true` if at least one priority was changed.
444    pub fn mark_ready(&mut self, project: &ProjectKey, is_ready: bool) -> bool {
445        let mut changed = false;
446        if let Some(project_key_pairs) = self.stacks_by_project.get(project) {
447            for project_key_pair in project_key_pairs {
448                self.priority_queue
449                    .change_priority_by(project_key_pair, |stack| {
450                        let mut found = false;
451                        for (subkey, readiness) in [
452                            (
453                                project_key_pair.own_key,
454                                &mut stack.readiness.own_project_ready,
455                            ),
456                            (
457                                project_key_pair.sampling_key,
458                                &mut stack.readiness.sampling_project_ready,
459                            ),
460                        ] {
461                            if subkey == *project {
462                                found = true;
463                                if *readiness != is_ready {
464                                    changed = true;
465                                    *readiness = is_ready;
466                                }
467                            }
468                        }
469                        debug_assert!(found);
470                    });
471            }
472        }
473
474        changed
475    }
476
477    /// Marks a stack as seen.
478    ///
479    /// Non-ready stacks are deprioritized when they are marked as seen, such that
480    /// the next call to `.peek()` will look at a different stack. This prevents
481    /// head-of-line blocking.
482    pub fn mark_seen(&mut self, project_key_pair: &ProjectKeyPair, next_fetch: Duration) {
483        self.priority_queue
484            .change_priority_by(project_key_pair, |stack| {
485                // We use the next project fetch to debounce project fetching and avoid head of
486                // line blocking of non-ready stacks.
487                stack.next_project_fetch = Instant::now() + next_fetch;
488            });
489    }
490
491    /// Returns `true` if the buffer contains no envelopes, in memory or on disk.
492    pub fn is_empty(&self) -> bool {
493        self.priority_queue.is_empty()
494    }
495
496    /// Returns `true` if the underlying storage has the capacity to store more envelopes.
497    pub fn has_capacity(&self) -> bool {
498        self.stack_provider.has_store_capacity()
499    }
500
501    /// Flushes the envelope buffer.
502    pub async fn flush(&mut self) {
503        let priority_queue = mem::take(&mut self.priority_queue);
504        self.stack_provider
505            .flush(priority_queue.into_iter().map(|(q, _)| q.value))
506            .await;
507    }
508
509    /// Pushes a new [`EnvelopeStack`] with the given [`Envelope`] inserted.
510    async fn push_stack(
511        &mut self,
512        stack_creation_type: StackCreationType,
513        project_key_pair: ProjectKeyPair,
514        envelope: Option<Box<Envelope>>,
515    ) -> Result<(), EnvelopeBufferError> {
516        let received_at = envelope.as_ref().map_or(Utc::now(), |e| e.received_at());
517
518        let mut stack = self
519            .stack_provider
520            .create_stack(stack_creation_type, project_key_pair);
521        if let Some(envelope) = envelope {
522            stack.push(envelope).await?;
523        }
524
525        let previous_entry = self.priority_queue.push(
526            QueueItem {
527                key: project_key_pair,
528                value: stack,
529            },
530            Priority::new(received_at),
531        );
532        debug_assert!(previous_entry.is_none());
533        for project_key in project_key_pair.iter() {
534            self.stacks_by_project
535                .entry(project_key)
536                .or_default()
537                .insert(project_key_pair);
538        }
539        relay_statsd::metric!(
540            gauge(RelayGauges::BufferStackCount) = self.priority_queue.len() as u64,
541            partition_id = &self.partition_tag
542        );
543
544        Ok(())
545    }
546
547    /// Pops an [`EnvelopeStack`] with the supplied [`EnvelopeBufferError`].
548    fn pop_stack(&mut self, project_key_pair: ProjectKeyPair) {
549        for project_key in project_key_pair.iter() {
550            self.stacks_by_project
551                .get_mut(&project_key)
552                .expect("project_key is missing from lookup")
553                .remove(&project_key_pair);
554        }
555        self.priority_queue.remove(&project_key_pair);
556
557        relay_statsd::metric!(
558            gauge(RelayGauges::BufferStackCount) = self.priority_queue.len() as u64,
559            partition_id = &self.partition_tag
560        );
561    }
562
563    /// Creates all the [`EnvelopeStack`]s with no data given a set of [`ProjectKeyPair`].
564    async fn load_stacks(&mut self, project_key_pairs: HashSet<ProjectKeyPair>) {
565        for project_key_pair in project_key_pairs {
566            self.push_stack(StackCreationType::Initialization, project_key_pair, None)
567                .await
568                .expect("Pushing an empty stack raised an error");
569        }
570    }
571
572    /// Loads the total count from the store if it takes less than a specified duration.
573    ///
574    /// The total count returned by the store is related to the count of elements that the buffer
575    /// will process, besides the count of elements that will be added and removed during its
576    /// lifecycle
577    async fn load_store_total_count(&mut self) {
578        let total_count = timeout(Duration::from_secs(1), async {
579            self.stack_provider.store_total_count().await
580        })
581        .await;
582        match total_count {
583            Ok(total_count) => {
584                self.total_count = total_count as i64;
585                self.total_count_initialized = true;
586            }
587            Err(error) => {
588                self.total_count_initialized = false;
589                relay_log::error!(
590                    error = &error as &dyn Error,
591                    "failed to load the total envelope count of the store",
592                );
593            }
594        };
595        self.track_total_count();
596    }
597
598    /// Emits a metric to track the total count of envelopes that are in the envelope buffer.
599    fn track_total_count(&self) {
600        let total_count = self.total_count as f64;
601        let initialized = match self.total_count_initialized {
602            true => "true",
603            false => "false",
604        };
605        relay_statsd::metric!(
606            gauge(RelayGauges::BufferEnvelopesCount) = total_count,
607            initialized = initialized,
608            stack_type = self.stack_provider.stack_type(),
609            partition_id = &self.partition_tag
610        );
611    }
612}
613
614/// Contains the state of the first element in the buffer.
615pub enum Peek {
616    Empty,
617    Ready {
618        project_key_pair: ProjectKeyPair,
619        last_received_at: DateTime<Utc>,
620    },
621    NotReady {
622        project_key_pair: ProjectKeyPair,
623        next_project_fetch: Instant,
624        last_received_at: DateTime<Utc>,
625    },
626}
627
628impl Peek {
629    pub fn last_received_at(&self) -> Option<DateTime<Utc>> {
630        match self {
631            Self::Empty => None,
632            Self::Ready {
633                last_received_at, ..
634            }
635            | Self::NotReady {
636                last_received_at, ..
637            } => Some(*last_received_at),
638        }
639    }
640}
641
642#[derive(Debug)]
643struct QueueItem<K, V> {
644    key: K,
645    value: V,
646}
647
648impl<K, V> std::borrow::Borrow<K> for QueueItem<K, V> {
649    fn borrow(&self) -> &K {
650        &self.key
651    }
652}
653
654impl<K: std::hash::Hash, V> std::hash::Hash for QueueItem<K, V> {
655    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
656        self.key.hash(state);
657    }
658}
659
660impl<K: PartialEq, V> PartialEq for QueueItem<K, V> {
661    fn eq(&self, other: &Self) -> bool {
662        self.key == other.key
663    }
664}
665
666impl<K: PartialEq, V> Eq for QueueItem<K, V> {}
667
668#[derive(Debug, Clone)]
669struct Priority {
670    readiness: Readiness,
671    received_at: DateTime<Utc>,
672    next_project_fetch: Instant,
673}
674
675impl Priority {
676    fn new(received_at: DateTime<Utc>) -> Self {
677        Self {
678            readiness: Readiness::new(),
679            received_at,
680            next_project_fetch: Instant::now(),
681        }
682    }
683}
684
685impl Ord for Priority {
686    fn cmp(&self, other: &Self) -> Ordering {
687        match (self.readiness.ready(), other.readiness.ready()) {
688            // Assuming that two priorities differ only w.r.t. the `last_peek`, we want to prioritize
689            // stacks that were the least recently peeked. The rationale behind this is that we want
690            // to keep cycling through different stacks while peeking.
691            (true, true) => self.received_at.cmp(&other.received_at),
692            (true, false) => Ordering::Greater,
693            (false, true) => Ordering::Less,
694            // For non-ready stacks, we invert the priority, such that projects that are not
695            // ready and did not receive envelopes recently can be evicted.
696            (false, false) => self
697                .next_project_fetch
698                .cmp(&other.next_project_fetch)
699                .reverse()
700                .then(self.received_at.cmp(&other.received_at).reverse()),
701        }
702    }
703}
704
705impl PartialOrd for Priority {
706    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
707        Some(self.cmp(other))
708    }
709}
710
711impl PartialEq for Priority {
712    fn eq(&self, other: &Self) -> bool {
713        self.cmp(other).is_eq()
714    }
715}
716
717impl Eq for Priority {}
718
719#[derive(Debug, Clone, Copy)]
720struct Readiness {
721    own_project_ready: bool,
722    sampling_project_ready: bool,
723}
724
725impl Readiness {
726    fn new() -> Self {
727        // Optimistically set ready state to true.
728        // The large majority of stack creations are re-creations after a stack was emptied.
729        Self {
730            own_project_ready: true,
731            sampling_project_ready: true,
732        }
733    }
734
735    fn ready(&self) -> bool {
736        self.own_project_ready && self.sampling_project_ready
737    }
738}
739
740#[cfg(test)]
741mod tests {
742    use std::str::FromStr;
743    use std::sync::Arc;
744
745    use relay_base_schema::project::ProjectId;
746    use relay_common::Dsn;
747    use relay_config::Config;
748    use relay_event_schema::protocol::EventId;
749    use relay_sampling::DynamicSamplingContext;
750    use uuid::Uuid;
751
752    use super::*;
753    use crate::SqliteEnvelopeStore;
754    use crate::envelope::TransactionItem;
755    use crate::extractors::RequestMeta;
756    use crate::services::buffer::common::ProjectKeyPair;
757    use crate::services::buffer::envelope_store::sqlite::DatabaseEnvelope;
758    use crate::services::buffer::testutils::utils::mock_envelopes;
759    use crate::utils::MemoryStat;
760
761    impl Peek {
762        fn is_empty(&self) -> bool {
763            matches!(self, Peek::Empty)
764        }
765    }
766
767    fn new_envelope(
768        own_key: ProjectKey,
769        sampling_key: Option<ProjectKey>,
770        event_id: Option<EventId>,
771    ) -> Box<Envelope> {
772        let mut envelope = Envelope::from_request(
773            None,
774            RequestMeta::new(Dsn::from_str(&format!("http://{own_key}@localhost/1")).unwrap()),
775        );
776        if let Some(sampling_key) = sampling_key {
777            envelope.set_dsc(DynamicSamplingContext {
778                public_key: sampling_key,
779                project_id: Some(ProjectId::new(42)),
780                trace_id: "67e5504410b1426f9247bb680e5fe0c8".parse().unwrap(),
781                release: None,
782                user: Default::default(),
783                replay_id: None,
784                environment: None,
785                transaction: None,
786                sample_rate: None,
787                sampled: None,
788                other: Default::default(),
789            });
790            envelope.add_item(TransactionItem::new());
791        }
792        if let Some(event_id) = event_id {
793            envelope.set_event_id(event_id);
794        }
795        envelope
796    }
797
798    fn mock_config(path: &str) -> Arc<Config> {
799        Config::from_json_value(serde_json::json!({
800            "spool": {
801                "envelopes": {
802                    "path": path
803                }
804            }
805        }))
806        .unwrap()
807        .into()
808    }
809
810    fn mock_memory_checker() -> MemoryChecker {
811        MemoryChecker::new(MemoryStat::default(), mock_config("my/db/path").clone())
812    }
813
814    async fn peek_received_at(buffer: &mut EnvelopeBuffer<MemoryStackProvider>) -> DateTime<Utc> {
815        buffer.peek().await.unwrap().last_received_at().unwrap()
816    }
817
818    #[tokio::test]
819    async fn test_insert_pop() {
820        let mut buffer = EnvelopeBuffer::<MemoryStackProvider>::new(0, mock_memory_checker());
821
822        let project_key1 = ProjectKey::parse("a94ae32be2584e0bbd7a4cbb95971fed").unwrap();
823        let project_key2 = ProjectKey::parse("a94ae32be2584e0bbd7a4cbb95971fee").unwrap();
824        let project_key3 = ProjectKey::parse("a94ae32be2584e0bbd7a4cbb95971fef").unwrap();
825
826        assert!(buffer.pop().await.unwrap().is_none());
827        assert!(buffer.peek().await.unwrap().is_empty());
828
829        let envelope1 = new_envelope(project_key1, None, None);
830        let time1 = envelope1.meta().received_at();
831        buffer.push(envelope1).await.unwrap();
832
833        let envelope2 = new_envelope(project_key2, None, None);
834        let time2 = envelope2.meta().received_at();
835        buffer.push(envelope2).await.unwrap();
836
837        // Both projects are ready, so project 2 is on top (has the newest envelopes):
838        assert_eq!(peek_received_at(&mut buffer).await, time2);
839
840        buffer.mark_ready(&project_key1, false);
841        buffer.mark_ready(&project_key2, false);
842
843        // Both projects are not ready, so project 1 is on top (has the oldest envelopes):
844        assert_eq!(peek_received_at(&mut buffer).await, time1);
845
846        let envelope3 = new_envelope(project_key3, None, None);
847        let time3 = envelope3.meta().received_at();
848        buffer.push(envelope3).await.unwrap();
849        buffer.mark_ready(&project_key3, false);
850
851        // All projects are not ready, so project 1 is on top (has the oldest envelopes):
852        assert_eq!(peek_received_at(&mut buffer).await, time1);
853
854        // After marking a project ready, it goes to the top:
855        buffer.mark_ready(&project_key3, true);
856        assert_eq!(peek_received_at(&mut buffer).await, time3);
857        assert_eq!(
858            buffer.pop().await.unwrap().unwrap().meta().public_key(),
859            project_key3
860        );
861
862        // After popping, project 1 is on top again:
863        assert_eq!(peek_received_at(&mut buffer).await, time1);
864
865        // Mark project 1 as ready (still on top):
866        buffer.mark_ready(&project_key1, true);
867        assert_eq!(peek_received_at(&mut buffer).await, time1);
868
869        // Mark project 2 as ready as well (now on top because most recent):
870        buffer.mark_ready(&project_key2, true);
871        assert_eq!(peek_received_at(&mut buffer).await, time2);
872        assert_eq!(
873            buffer.pop().await.unwrap().unwrap().meta().public_key(),
874            project_key2
875        );
876
877        // Pop last element:
878        assert_eq!(
879            buffer.pop().await.unwrap().unwrap().meta().public_key(),
880            project_key1
881        );
882        assert!(buffer.pop().await.unwrap().is_none());
883        assert!(buffer.peek().await.unwrap().is_empty());
884    }
885
886    #[tokio::test]
887    async fn test_project_internal_order() {
888        let mut buffer = EnvelopeBuffer::<MemoryStackProvider>::new(0, mock_memory_checker());
889
890        let project_key = ProjectKey::parse("a94ae32be2584e0bbd7a4cbb95971fed").unwrap();
891
892        let envelope1 = new_envelope(project_key, None, None);
893        let time1 = envelope1.meta().received_at();
894        let envelope2 = new_envelope(project_key, None, None);
895        let time2 = envelope2.meta().received_at();
896
897        assert!(time2 > time1);
898
899        buffer.push(envelope1).await.unwrap();
900        buffer.push(envelope2).await.unwrap();
901
902        assert_eq!(
903            buffer.pop().await.unwrap().unwrap().meta().received_at(),
904            time2
905        );
906        assert_eq!(
907            buffer.pop().await.unwrap().unwrap().meta().received_at(),
908            time1
909        );
910        assert!(buffer.pop().await.unwrap().is_none());
911    }
912
913    #[tokio::test]
914    async fn test_sampling_projects() {
915        let mut buffer = EnvelopeBuffer::<MemoryStackProvider>::new(0, mock_memory_checker());
916
917        let project_key1 = ProjectKey::parse("a94ae32be2584e0bbd7a4cbb95971fed").unwrap();
918        let project_key2 = ProjectKey::parse("a94ae32be2584e0bbd7a4cbb95971fef").unwrap();
919
920        let envelope1 = new_envelope(project_key1, None, None);
921        let time1 = envelope1.received_at();
922        buffer.push(envelope1).await.unwrap();
923
924        let envelope2 = new_envelope(project_key2, None, None);
925        let time2 = envelope2.received_at();
926        buffer.push(envelope2).await.unwrap();
927
928        let envelope3 = new_envelope(project_key1, Some(project_key2), None);
929        let time3 = envelope3.meta().received_at();
930        buffer.push(envelope3).await.unwrap();
931
932        buffer.mark_ready(&project_key1, false);
933        buffer.mark_ready(&project_key2, false);
934
935        // Nothing is ready, instant1 is on top:
936        assert_eq!(
937            buffer.peek().await.unwrap().last_received_at().unwrap(),
938            time1
939        );
940
941        // Mark project 2 ready, gets on top:
942        buffer.mark_ready(&project_key2, true);
943        assert_eq!(
944            buffer.peek().await.unwrap().last_received_at().unwrap(),
945            time2
946        );
947
948        // Revert
949        buffer.mark_ready(&project_key2, false);
950        assert_eq!(
951            buffer.peek().await.unwrap().last_received_at().unwrap(),
952            time1
953        );
954
955        // Project 1 ready:
956        buffer.mark_ready(&project_key1, true);
957        assert_eq!(
958            buffer.peek().await.unwrap().last_received_at().unwrap(),
959            time1
960        );
961
962        // when both projects are ready, event no 3 ends up on top:
963        buffer.mark_ready(&project_key2, true);
964        assert_eq!(
965            buffer.pop().await.unwrap().unwrap().meta().received_at(),
966            time3
967        );
968        assert_eq!(
969            buffer.peek().await.unwrap().last_received_at().unwrap(),
970            time2
971        );
972
973        buffer.mark_ready(&project_key2, false);
974        assert_eq!(buffer.pop().await.unwrap().unwrap().received_at(), time1);
975        assert_eq!(buffer.pop().await.unwrap().unwrap().received_at(), time2);
976
977        assert!(buffer.pop().await.unwrap().is_none());
978    }
979
980    #[tokio::test]
981    async fn test_project_keys_distinct() {
982        let project_key1 = ProjectKey::parse("a94ae32be2584e0bbd7a4cbb95971fed").unwrap();
983        let project_key2 = ProjectKey::parse("a94ae32be2584e0bbd7a4cbb95971fef").unwrap();
984
985        let project_key_pair1 = ProjectKeyPair::new(project_key1, project_key2);
986        let project_key_pair2 = ProjectKeyPair::new(project_key2, project_key1);
987
988        assert_ne!(project_key_pair1, project_key_pair2);
989
990        let mut buffer = EnvelopeBuffer::<MemoryStackProvider>::new(0, mock_memory_checker());
991        buffer
992            .push(new_envelope(project_key1, Some(project_key2), None))
993            .await
994            .unwrap();
995        buffer
996            .push(new_envelope(project_key2, Some(project_key1), None))
997            .await
998            .unwrap();
999        assert_eq!(buffer.priority_queue.len(), 2);
1000    }
1001
1002    #[test]
1003    fn test_total_order() {
1004        let p1 = Priority {
1005            readiness: Readiness {
1006                own_project_ready: true,
1007                sampling_project_ready: true,
1008            },
1009            received_at: Utc::now(),
1010            next_project_fetch: Instant::now(),
1011        };
1012        let mut p2 = p1.clone();
1013        p2.next_project_fetch += Duration::from_millis(1);
1014
1015        // Last peek does not matter because project is ready:
1016        assert_eq!(p1.cmp(&p2), Ordering::Equal);
1017        assert_eq!(p1, p2);
1018    }
1019
1020    #[tokio::test]
1021    async fn test_last_peek_internal_order() {
1022        let mut buffer = EnvelopeBuffer::<MemoryStackProvider>::new(0, mock_memory_checker());
1023
1024        let project_key_1 = ProjectKey::parse("a94ae32be2584e0bbd7a4cbb95971fed").unwrap();
1025        let event_id_1 = EventId::new();
1026        let envelope1 = new_envelope(project_key_1, None, Some(event_id_1));
1027        let time1 = envelope1.received_at();
1028
1029        let project_key_2 = ProjectKey::parse("b56ae32be2584e0bbd7a4cbb95971fed").unwrap();
1030        let event_id_2 = EventId::new();
1031        let envelope2 = new_envelope(project_key_2, None, Some(event_id_2));
1032        let time2 = envelope2.received_at();
1033
1034        buffer.push(envelope1).await.unwrap();
1035        buffer.push(envelope2).await.unwrap();
1036
1037        buffer.mark_ready(&project_key_1, false);
1038        buffer.mark_ready(&project_key_2, false);
1039
1040        // event_id_1 is first element:
1041        let Peek::NotReady {
1042            last_received_at, ..
1043        } = buffer.peek().await.unwrap()
1044        else {
1045            panic!();
1046        };
1047        assert_eq!(last_received_at, time1);
1048
1049        // Second peek returns same element:
1050        let Peek::NotReady {
1051            last_received_at,
1052            project_key_pair,
1053            ..
1054        } = buffer.peek().await.unwrap()
1055        else {
1056            panic!();
1057        };
1058        assert_eq!(last_received_at, time1);
1059        assert_ne!(last_received_at, time2);
1060
1061        buffer.mark_seen(&project_key_pair, Duration::ZERO);
1062
1063        // After mark_seen, event 2 is on top:
1064        let Peek::NotReady {
1065            last_received_at, ..
1066        } = buffer.peek().await.unwrap()
1067        else {
1068            panic!();
1069        };
1070        assert_eq!(last_received_at, time2);
1071        assert_ne!(last_received_at, time1);
1072
1073        let Peek::NotReady {
1074            last_received_at,
1075            project_key_pair,
1076            ..
1077        } = buffer.peek().await.unwrap()
1078        else {
1079            panic!();
1080        };
1081        assert_eq!(last_received_at, time2);
1082        assert_ne!(last_received_at, time1);
1083
1084        buffer.mark_seen(&project_key_pair, Duration::ZERO);
1085
1086        // After another mark_seen, cycle back to event 1:
1087        let Peek::NotReady {
1088            last_received_at, ..
1089        } = buffer.peek().await.unwrap()
1090        else {
1091            panic!();
1092        };
1093        assert_eq!(last_received_at, time1);
1094        assert_ne!(last_received_at, time2);
1095    }
1096
1097    #[tokio::test]
1098    async fn test_initialize_buffer() {
1099        let path = std::env::temp_dir()
1100            .join(Uuid::new_v4().to_string())
1101            .into_os_string()
1102            .into_string()
1103            .unwrap();
1104        let config = mock_config(&path);
1105        let current_config = config.current();
1106        let mut store = SqliteEnvelopeStore::prepare(0, &current_config)
1107            .await
1108            .unwrap();
1109        let mut buffer = EnvelopeBuffer::<SqliteStackProvider>::new(
1110            0,
1111            &current_config,
1112            Arc::new(Throttle::new(None)),
1113        )
1114        .await
1115        .unwrap();
1116
1117        // We write 5 envelopes to disk so that we can check if they are loaded. These envelopes
1118        // belong to the same project keys, so they belong to the same envelope stack.
1119        let envelopes = mock_envelopes(10);
1120        assert!(
1121            store
1122                .insert_batch(
1123                    envelopes
1124                        .into_iter()
1125                        .map(|e| DatabaseEnvelope::try_from(e.as_ref()).unwrap())
1126                        .collect::<Vec<_>>()
1127                        .try_into()
1128                        .unwrap()
1129                )
1130                .await
1131                .is_ok()
1132        );
1133
1134        // We assume that the buffer is empty.
1135        assert!(buffer.priority_queue.is_empty());
1136        assert!(buffer.stacks_by_project.is_empty());
1137
1138        buffer.initialize().await;
1139
1140        // We assume that we loaded only 1 envelope stack, because of the project keys combinations
1141        // of the envelopes we inserted above.
1142        assert_eq!(buffer.priority_queue.len(), 1);
1143        // We expect to have an entry per project key, since we have 1 pair, the total entries
1144        // should be 2.
1145        assert_eq!(buffer.stacks_by_project.len(), 2);
1146    }
1147}