Skip to main content

lb_rs/io/
copy.rs

1//! Independent copies of in-memory instances, for tests that build a world once and start many
2//! cases from it.
3use crate::io::docs::LocalDocuments;
4
5use db_rs::View;
6use db_rs::config::Config as DbConfig;
7use db_rs::errors::Result as DbResult;
8use db_rs::views::composite_view::{Composite, Schema};
9
10use crate::Lb;
11use crate::io::CoreDb;
12use crate::io::server::Server;
13use crate::model::core_config::Config;
14use crate::model::errors::{LbErrKind, LbResult};
15use crate::service::logging;
16
17/// An in-memory database holding what `db` holds, sharing nothing with it. Every table restarts
18/// at sequence number zero, as the copy's log does.
19pub fn copy_db<S: Schema>(db: &mut Composite<S>) -> DbResult<Composite<S>> {
20    let mut copy = Composite::<S>::init(&DbConfig::in_memory())?;
21    let mut tables = db.schema.views_mut();
22    let mut copies = copy.schema.views_mut();
23    for (table, copy) in tables.as_mut().iter_mut().zip(copies.as_mut().iter_mut()) {
24        copy.handle_events(0, &table.generate_snapshot()?)?;
25    }
26    drop(copies);
27    Ok(copy)
28}
29
30impl<S: Server, D: LocalDocuments> Lb<S, D> {
31    /// An in-memory instance holding this one's database and the documents `docs` copies from
32    /// this one's, sharing nothing with it, configured by `config` and sending every request to
33    /// `server`. It starts as this instance would after a restart: nothing in flight, caches
34    /// empty. Waits for any sync in progress.
35    pub async fn copy_in_memory<T: Server, E: LocalDocuments>(
36        &self, config: Config, server: T, docs: impl FnOnce(&D) -> E,
37    ) -> LbResult<Lb<T, E>> {
38        let _syncing = self.syncer.lock().await;
39        let mut db = self.db.write().await;
40        let db: CoreDb =
41            copy_db(&mut db).map_err(|err| LbErrKind::Unexpected(format!("{err:?}")))?;
42        let docs = docs(&self.docs);
43
44        logging::init(&config)?;
45        Lb::assemble(
46            config,
47            db,
48            docs,
49            server,
50            #[cfg(all(unix, not(target_os = "ios")))]
51            None,
52            #[cfg(not(any(target_family = "wasm", target_os = "ios")))]
53            None,
54        )
55        .await
56    }
57}