1use 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#[derive(Clone, Debug)]
65pub struct FdbConsensusConfig {
66 url: SensitiveUrl,
67}
68
69impl FdbConsensusConfig {
70 pub fn new(url: SensitiveUrl) -> Result<Self, Error> {
72 Ok(FdbConsensusConfig { url })
73 }
74}
75
76pub struct FdbConsensus {
78 keys: DirectorySubspace,
80 data: DirectorySubspace,
82 db: Database,
84}
85
86enum 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 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 #[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 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 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 let current = self.head_trx(trx, data_key, false).await?;
245 let current_seqno = current.map(|v| v.seqno);
246
247 if expected != ¤t_seqno {
248 return Ok(CaSResult::ExpectationMismatch);
249 }
250
251 if expected.is_none() {
252 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 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 |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 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)] 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 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(consensus);
519 mz_foundationdb::shutdown_network();
520 Ok(())
521 }
522}