Skip to main content

mz_persist/
foundationdb.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Implementation of [Consensus] backed by FoundationDB.
11//!
12//! We're storing the consensus data in a subspace. Each key maps to a subspace
13//! with the following structure:
14//! * `./keys/<key> -> ()` to track existing keys.
15//! * `./data/<key>/<seqno> -> <data>` mapping seqnos to data blobs.
16//!
17//! The current seqno for a key is determined by a reverse scan of the data
18//! entries, rather than a separate head pointer. This ensures locality between
19//! the latest data and any metadata lookups.
20
21use std::io::Write;
22
23use anyhow::anyhow;
24use async_stream::try_stream;
25use async_trait::async_trait;
26use bytes::Bytes;
27use futures_util::future::FutureExt;
28use mz_foundationdb::FdbConfig;
29use mz_foundationdb::directory::{
30    Directory, DirectoryError, DirectoryLayer, DirectoryOutput, DirectorySubspace,
31};
32use mz_foundationdb::tuple::{
33    PackError, PackResult, Subspace, TupleDepth, TuplePack, TupleUnpack, VersionstampOffset,
34};
35use mz_foundationdb::{
36    Database, FdbBindingError, FdbError, KeySelector, RangeOption, TransactError, TransactOption,
37    Transaction,
38};
39use mz_ore::url::SensitiveUrl;
40
41use crate::error::Error;
42use crate::location::{
43    CaSResult, Consensus, Determinate, ExternalError, Indeterminate, ResultStream, SeqNo,
44    VersionedData,
45};
46
47impl From<FdbError> for ExternalError {
48    fn from(x: FdbError) -> Self {
49        if x.is_retryable() {
50            ExternalError::Indeterminate(Indeterminate::new(x.into()))
51        } else {
52            ExternalError::Determinate(Determinate::new(x.into()))
53        }
54    }
55}
56
57impl From<FdbBindingError> for ExternalError {
58    fn from(x: FdbBindingError) -> Self {
59        ExternalError::Determinate(Determinate::new(x.into()))
60    }
61}
62
63/// Configuration to connect to a FoundationDB backed implementation of [Consensus].
64#[derive(Clone, Debug)]
65pub struct FdbConsensusConfig {
66    url: SensitiveUrl,
67}
68
69impl FdbConsensusConfig {
70    /// Returns a new [FdbConsensusConfig] for use in production.
71    pub fn new(url: SensitiveUrl) -> Result<Self, Error> {
72        Ok(FdbConsensusConfig { url })
73    }
74}
75
76/// Implementation of [Consensus] over a Foundation database.
77pub struct FdbConsensus {
78    /// Subspace for data.
79    keys: DirectorySubspace,
80    /// Subspace for data.
81    data: DirectorySubspace,
82    /// The FoundationDB database handle.
83    db: Database,
84}
85
86/// An error that can occur during a FoundationDB transaction.
87/// This is either a FoundationDB error or an external error.
88enum FdbTransactError {
89    FdbError(FdbError),
90    ExternalError(ExternalError),
91}
92
93impl From<FdbError> for FdbTransactError {
94    fn from(value: FdbError) -> Self {
95        Self::FdbError(value)
96    }
97}
98
99impl From<ExternalError> for FdbTransactError {
100    fn from(value: ExternalError) -> Self {
101        Self::ExternalError(value)
102    }
103}
104
105impl From<PackError> for FdbTransactError {
106    fn from(value: PackError) -> Self {
107        ExternalError::Determinate(anyhow::Error::new(value).into()).into()
108    }
109}
110
111impl From<FdbTransactError> for ExternalError {
112    fn from(value: FdbTransactError) -> Self {
113        match value {
114            FdbTransactError::FdbError(e) => e.into(),
115            FdbTransactError::ExternalError(e) => e,
116        }
117    }
118}
119
120impl From<DirectoryError> for ExternalError {
121    fn from(e: DirectoryError) -> Self {
122        ExternalError::Determinate(anyhow!("directory error: {e:?}").into())
123    }
124}
125
126impl TransactError for FdbTransactError {
127    fn try_into_fdb_error(self) -> Result<FdbError, Self> {
128        match self {
129            Self::FdbError(e) => Ok(e),
130            other => Err(other),
131        }
132    }
133}
134
135impl TuplePack for SeqNo {
136    fn pack<W: Write>(
137        &self,
138        w: &mut W,
139        tuple_depth: TupleDepth,
140    ) -> std::io::Result<VersionstampOffset> {
141        self.0.pack(w, tuple_depth)
142    }
143}
144
145impl<'de> TupleUnpack<'de> for SeqNo {
146    fn unpack(input: &'de [u8], tuple_depth: TupleDepth) -> PackResult<(&'de [u8], Self)> {
147        u64::unpack(input, tuple_depth).map(|(rem, v)| (rem, SeqNo(v)))
148    }
149}
150
151impl std::fmt::Debug for FdbConsensus {
152    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153        f.debug_struct("FdbConsensus")
154            .field("keys", &self.keys)
155            .field("data", &self.data)
156            .finish_non_exhaustive()
157    }
158}
159
160impl FdbConsensus {
161    /// Open a FoundationDB [Consensus] instance with `config`.
162    pub async fn open(config: FdbConsensusConfig) -> Result<Self, ExternalError> {
163        let fdb_config =
164            FdbConfig::parse(&config.url).map_err(|e| ExternalError::Determinate(e.into()))?;
165
166        mz_foundationdb::init_network();
167
168        let db = Database::new(None)?;
169        // In tests, bound transactions so an unresponsive server fails fast
170        // instead of hanging until the harness terminates the process.
171        #[cfg(test)]
172        mz_foundationdb::set_test_transaction_timeout(&db);
173        let directory = DirectoryLayer::default();
174        let keys_path: Vec<_> = fdb_config
175            .prefix
176            .iter()
177            .cloned()
178            .chain(std::iter::once("keys".to_owned()))
179            .collect();
180        let keys = Self::open_directory(&db, &directory, &keys_path).await?;
181        let data_path: Vec<_> = fdb_config
182            .prefix
183            .into_iter()
184            .chain(std::iter::once("data".to_owned()))
185            .collect();
186        let data = Self::open_directory(&db, &directory, &data_path).await?;
187        Ok(FdbConsensus { keys, data, db })
188    }
189
190    /// Opens (or creates) a directory at the specified path. Errors if the
191    /// directory is a partition, or cannot be opened for another reason..
192    async fn open_directory(
193        db: &Database,
194        directory: &DirectoryLayer,
195        path: &[String],
196    ) -> Result<DirectorySubspace, ExternalError> {
197        let directory = db
198            .run(async |trx, _maybe_commited| {
199                Ok(directory.create_or_open(&trx, path, None, None).await)
200            })
201            .await??;
202        match directory {
203            DirectoryOutput::DirectorySubspace(subspace) => Ok(subspace),
204            DirectoryOutput::DirectoryPartition(_partition) => Err(ExternalError::from(anyhow!(
205                "consensus data cannot be a partition"
206            ))),
207        }
208    }
209
210    /// Returns the latest entry for a key by reverse scanning the data entries.
211    ///
212    /// If `snapshot` is true, uses snapshot reads which don't create conflict
213    /// ranges. Use snapshot=true for read-only `head()` calls, and snapshot=false
214    /// for `compare_and_set()` where we need conflict detection.
215    async fn head_trx(
216        &self,
217        trx: &Transaction,
218        data_key: &Subspace,
219        snapshot: bool,
220    ) -> Result<Option<VersionedData>, FdbTransactError> {
221        let mut range = RangeOption::from(data_key).rev();
222        range.limit = Some(1);
223        range.mode = mz_foundationdb::options::StreamingMode::Exact;
224        let values = trx.get_range(&range, 1, snapshot).await?;
225        if let Some(kv) = values.first() {
226            let seqno = data_key.unpack(kv.key())?;
227            Ok(Some(VersionedData {
228                seqno,
229                data: Bytes::from(kv.value().to_vec()),
230            }))
231        } else {
232            Ok(None)
233        }
234    }
235    async fn compare_and_set_trx(
236        &self,
237        trx: &Transaction,
238        data_key: &Subspace,
239        expected: &Option<SeqNo>,
240        new: &VersionedData,
241        key: &str,
242    ) -> Result<CaSResult, FdbTransactError> {
243        // Use non-snapshot read to create conflict ranges for concurrent writes.
244        let current = self.head_trx(trx, data_key, false).await?;
245        let current_seqno = current.map(|v| v.seqno);
246
247        if expected != &current_seqno {
248            return Ok(CaSResult::ExpectationMismatch);
249        }
250
251        if expected.is_none() {
252            // If expected is `None`, it's a new key which we need to register in the keys directory.
253            let key = self.keys.pack(&key);
254            trx.set(&key, &[]);
255        }
256
257        let data_seqno_key = data_key.pack(&new.seqno);
258        trx.set(&data_seqno_key, new.data.as_ref());
259        Ok(CaSResult::Committed)
260    }
261
262    async fn scan_trx(
263        &self,
264        trx: &Transaction,
265        data_key: &Subspace,
266        from: &SeqNo,
267        limit: &usize,
268        entries: &mut Vec<VersionedData>,
269    ) -> Result<(), FdbTransactError> {
270        let seqno_start = data_key.pack(&from);
271        let seqno_end = data_key.pack(&SeqNo::maximum());
272
273        let mut range = RangeOption::from(seqno_start..=seqno_end);
274        range.limit = Some(*limit);
275
276        entries.clear();
277
278        loop {
279            let output = trx.get_range(&range, 1, false).await?;
280            entries.reserve(output.len());
281            for key_value in &output {
282                let seqno = data_key.unpack(key_value.key())?;
283                entries.push(VersionedData {
284                    seqno,
285                    data: Bytes::from(key_value.value().to_vec()),
286                });
287            }
288
289            if let Some(next_range) = range.next_range(&output) {
290                range = next_range;
291            } else {
292                break;
293            }
294        }
295        Ok(())
296    }
297
298    async fn truncate_trx(
299        &self,
300        trx: &Transaction,
301        data_key: &Subspace,
302        until: &SeqNo,
303    ) -> Result<(), FdbTransactError> {
304        // Snapshot read is fine here - truncate is idempotent and the validation
305        // only gets more permissive if a concurrent CaS increases the seqno.
306        let current = self.head_trx(trx, data_key, true).await?;
307        if let Some(current) = current {
308            if current.seqno < *until {
309                return Err(ExternalError::Determinate(
310                    anyhow!("upper bound too high for truncate: {until}").into(),
311                )
312                .into());
313            }
314        } else {
315            return Err(ExternalError::Determinate(anyhow!("no entries for key").into()).into());
316        }
317        let key_space_start = data_key.pack(&SeqNo::minimum());
318        let key_space_end = data_key.pack(&until);
319
320        trx.clear_range(&key_space_start, &key_space_end);
321        Ok(())
322    }
323}
324
325#[async_trait]
326impl Consensus for FdbConsensus {
327    fn list_keys(&self) -> ResultStream<'_, String> {
328        Box::pin(try_stream! {
329            let keys: Vec<String> = self
330                .db
331                .run(async |trx, _maybe_commited| {
332                    let mut range = RangeOption::from(self.keys.range());
333                    let mut keys = Vec::new();
334                    loop {
335                        let values = trx.get_range(&range, 1, false).await?;
336                        for value in &values {
337                            let key: String = self.keys.unpack(value.key())
338                                .map_err(FdbBindingError::PackError)?;
339                            keys.push(key);
340                        }
341                        if let Some(last) = values.last() {
342                            range.begin = KeySelector::first_greater_than(last.key().to_vec());
343                        } else {
344                            break;
345                        }
346                    }
347                    Ok(keys)
348                }).await?;
349
350            for shard in keys {
351                yield shard;
352            }
353        })
354    }
355
356    async fn head(&self, key: &str) -> Result<Option<VersionedData>, ExternalError> {
357        let data_key = self.data.subspace(&key);
358
359        let ok = self
360            .db
361            .transact_boxed(
362                &data_key,
363                // Use snapshot read - we don't need strict consistency for head().
364                |trx, data_key| self.head_trx(trx, data_key, true).boxed(),
365                TransactOption::default(),
366            )
367            .await?;
368        Ok(ok)
369    }
370
371    async fn compare_and_set(
372        &self,
373        key: &str,
374        new: VersionedData,
375    ) -> Result<CaSResult, ExternalError> {
376        let expected = new.seqno.previous();
377        if new.seqno.0 > i64::MAX.try_into().expect("i64::MAX known to fit in u64") {
378            return Err(ExternalError::from(anyhow!(
379                "sequence numbers must fit within [0, i64::MAX], received: {:?}",
380                new.seqno
381            )));
382        }
383
384        let data_key = self.data.subspace(&key);
385
386        let ok = self
387            .db
388            .transact_boxed(
389                (expected, &new, &*key),
390                |trx, (expected, new, key)| {
391                    self.compare_and_set_trx(trx, &data_key, expected, new, key)
392                        .boxed()
393                },
394                TransactOption::default(),
395            )
396            .await?;
397        Ok(ok)
398    }
399
400    async fn scan(
401        &self,
402        key: &str,
403        from: SeqNo,
404        limit: usize,
405    ) -> Result<Vec<VersionedData>, ExternalError> {
406        let data_key = self.data.subspace(&key);
407        let mut entries = Vec::new();
408        self.db
409            .transact_boxed(
410                (&data_key, from, limit, &mut entries),
411                |trx, (data_key, from, limit, entries)| {
412                    self.scan_trx(trx, data_key, from, limit, entries).boxed()
413                },
414                TransactOption::default(),
415            )
416            .await?;
417
418        entries.sort_by_key(|e| e.seqno);
419        Ok(entries)
420    }
421
422    async fn truncate(&self, key: &str, seqno: SeqNo) -> Result<Option<usize>, ExternalError> {
423        let data_key = self.data.subspace(&key);
424
425        self.db
426            .transact_boxed(
427                (&data_key, seqno),
428                |trx, (data_key, seqno)| self.truncate_trx(trx, data_key, seqno).boxed(),
429                TransactOption::idempotent(),
430            )
431            .await?;
432        Ok(None)
433    }
434}
435
436#[cfg(test)]
437mod tests {
438    use super::*;
439
440    use mz_foundationdb::directory::Directory;
441    use uuid::Uuid;
442
443    use crate::location::tests::consensus_impl_test;
444
445    /// Drops and recreates the `consensus` data in FoundationDB.
446    ///
447    /// ONLY FOR TESTING
448    async fn drop_and_recreate(consensus: &FdbConsensus) -> Result<(), ExternalError> {
449        consensus
450            .db
451            .run(async |trx, _maybe_commited| {
452                consensus.keys.remove(&trx, &[]).await?;
453                consensus.data.remove(&trx, &[]).await?;
454                Ok(())
455            })
456            .await?;
457        Ok(())
458    }
459
460    #[mz_ore::test(tokio::test(flavor = "multi_thread"))]
461    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `TLS_client_method` on OS `linux`
462    async fn fdb_consensus() -> Result<(), ExternalError> {
463        let config = FdbConsensusConfig::new(
464            std::str::FromStr::from_str("foundationdb:?prefix=test/consensus").unwrap(),
465        )?;
466
467        {
468            let fdb = FdbConsensus::open(config.clone()).await?;
469            drop_and_recreate(&fdb).await?;
470        }
471
472        consensus_impl_test(|| FdbConsensus::open(config.clone())).await?;
473
474        // and now verify the implementation-specific `drop_and_recreate` works as intended
475        let consensus = FdbConsensus::open(config.clone()).await?;
476        let key = Uuid::new_v4().to_string();
477        let mut state = VersionedData {
478            seqno: SeqNo(0),
479            data: Bytes::from("abc"),
480        };
481
482        assert_eq!(
483            consensus.compare_and_set(&key, state.clone()).await,
484            Ok(CaSResult::Committed),
485        );
486        state.seqno = SeqNo(1);
487        assert_eq!(
488            consensus.compare_and_set(&key, state.clone()).await,
489            Ok(CaSResult::Committed),
490        );
491        state.seqno = SeqNo(2);
492        assert_eq!(
493            consensus.compare_and_set(&key, state.clone()).await,
494            Ok(CaSResult::Committed),
495        );
496
497        assert_eq!(consensus.head(&key).await, Ok(Some(state.clone())));
498
499        println!("--- SCANNING ---");
500
501        for data in consensus.scan(&key, SeqNo(2), 10).await? {
502            println!(
503                "scan data: seqno: {:?}, {} bytes",
504                data.seqno,
505                data.data.len()
506            );
507        }
508
509        drop_and_recreate(&consensus).await?;
510
511        assert_eq!(consensus.head(&key).await, Ok(None));
512
513        // Drop all FoundationDB handles before stopping the network, then shut it
514        // down. The network must be stopped before the process exits, otherwise
515        // the client can segfault during teardown. Stopping it while a `Database`
516        // is still alive can instead block on the network thread join, so drop
517        // `consensus` first.
518        drop(consensus);
519        mz_foundationdb::shutdown_network();
520        Ok(())
521    }
522}