Skip to main content

lb_rs/io/
mod.rs

1//! Members of this model are concerned with the details of IO, generally
2//! disk and network. This is the module any on-disk migrations will live
3//! and ideas around network, disk, and memory caches will be expressed.
4//! Code here should not be platform dependent, and should strive to be
5//! suitable for a range of devices: iPhones with flaky networks to servers
6//! and workstations with excellent networks.
7
8pub mod copy;
9pub mod docs;
10pub mod legacy;
11pub mod network;
12pub mod server;
13
14use crate::Lb;
15use crate::model::account::Account;
16use crate::model::file_metadata::Owner;
17use crate::model::signed_meta::SignedMeta;
18use crate::service::activity::DocEvent;
19use crate::service::budget::lock_budget;
20use crate::service::lb_id::LbID;
21use crate::service::lock_shame::lock_budget_destroyed;
22#[cfg(all(unix, not(target_os = "ios")))]
23use crate::subscribers::ipc::Ipc;
24use db_rs::View;
25use db_rs::config::Config;
26use db_rs::errors::Result as DbResult;
27use db_rs::guard::WriteTx;
28use db_rs::views::{
29    composite_view::{Composite, Schema},
30    hashmap::DbHashMap,
31    option::DbOption,
32    vec::DbVec,
33};
34use db_rs_old::hasher::UuidIdentityHasherBuilder;
35use db_rs_old::{Config as OldConfig, Db};
36use legacy::CoreV4;
37use std::error::Error;
38use std::fs;
39use std::path::Path;
40use std::sync::Arc;
41use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
42use uuid::Uuid;
43use web_time::{Duration, Instant};
44
45pub(crate) type LbDb = Arc<RwLock<CoreDb>>;
46// todo: limit visibility
47pub type CoreDb = Composite<CoreV5>;
48pub type MigrationResult<T> = Result<T, Box<dyn Error + Send + Sync>>;
49
50#[derive(Default)]
51pub struct CoreV5 {
52    pub account: DbOption<Account>,
53    pub last_synced: DbOption<i64>,
54    pub root: DbOption<Uuid>,
55    pub local_metadata: DbHashMap<Uuid, SignedMeta, UuidIdentityHasherBuilder>,
56    pub base_metadata: DbHashMap<Uuid, SignedMeta, UuidIdentityHasherBuilder>,
57
58    /// map from pub key to username
59    pub pub_key_lookup: DbHashMap<Owner, String>,
60
61    pub doc_events: DbVec<DocEvent>,
62    pub id: DbOption<LbID>,
63    pub pinned_files: DbVec<Uuid>,
64
65    /// Sentinel for `send_debug_info` throttling: the millisecond timestamp of the
66    /// most recent panic file we've already uploaded. `None` means we have never
67    /// sent debug info; `Some(0)` means we've sent before but no panic file existed.
68    pub last_extracted_panic: DbOption<i64>,
69
70    pub searched_files: DbVec<Uuid>,
71}
72
73impl Schema for CoreV5 {
74    fn views_mut(&mut self) -> impl AsMut<[&mut dyn View]> {
75        let views: [&mut dyn View; 11] = [
76            &mut self.account,
77            &mut self.last_synced,
78            &mut self.root,
79            &mut self.local_metadata,
80            &mut self.base_metadata,
81            &mut self.pub_key_lookup,
82            &mut self.doc_events,
83            &mut self.id,
84            &mut self.pinned_files,
85            &mut self.last_extracted_panic,
86            &mut self.searched_files,
87        ];
88        views
89    }
90}
91
92pub fn init_read_only(path: &Path) -> MigrationResult<CoreDb> {
93    Ok(CoreDb::init(
94        &Config::default()
95            .log_location(path.join("CoreV5"))
96            .read_only(),
97    )?)
98}
99
100pub fn init_with_migration(path: &Path) -> MigrationResult<CoreDb> {
101    let directory = path.join("CoreV5");
102    fs::create_dir_all(&directory)?;
103    let mut db = CoreDb::init(&Config::default().log_location(directory))?;
104    if let Some(bytes) = db.log_mut().take_incomplete_write() {
105        error!(bytes, "discarded an incomplete database write");
106    }
107    let old_path = path.join("CoreV4.db");
108
109    if db.schema.account.is_none() {
110        if !old_path.try_exists()? && !path.join("CoreV4").try_exists()? {
111            return Ok(db);
112        }
113        let source = CoreV4::init(OldConfig {
114            create_db: false,
115            create_path: false,
116            ..OldConfig::in_folder(path)
117        })?;
118        let tx = db.write_tx()?;
119        let dest = &mut db.schema;
120        if let Some(value) = source.account.get() {
121            dest.account.replace(value.clone())?;
122        }
123        if let Some(value) = source.last_synced.get() {
124            dest.last_synced.replace(*value)?;
125        }
126        if let Some(value) = source.root.get() {
127            dest.root.replace(*value)?;
128        }
129        for (key, value) in source.local_metadata.get() {
130            dest.local_metadata.insert(*key, value.clone())?;
131        }
132        for (key, value) in source.base_metadata.get() {
133            dest.base_metadata.insert(*key, value.clone())?;
134        }
135        for (key, value) in source.pub_key_lookup.get() {
136            dest.pub_key_lookup.insert(*key, value.clone())?;
137        }
138        for value in source.doc_events.get() {
139            dest.doc_events.push(*value)?;
140        }
141        if let Some(value) = source.id.get() {
142            dest.id.replace(*value)?;
143        }
144        for value in source.pinned_files.get() {
145            dest.pinned_files.push(*value)?;
146        }
147        if let Some(value) = source.last_extracted_panic.get() {
148            dest.last_extracted_panic.replace(*value)?;
149        }
150        tx.end_tx(&mut db)?;
151        drop(source);
152        fs::remove_file(old_path)?;
153    }
154    Ok(db)
155}
156
157pub struct LbRO<'a> {
158    guard: RwLockReadGuard<'a, CoreDb>,
159    budget_start: Option<Instant>,
160}
161
162impl LbRO<'_> {
163    pub fn db(&self) -> &CoreV5 {
164        &self.guard.schema
165    }
166}
167
168pub struct LbTx<'a> {
169    guard: RwLockWriteGuard<'a, CoreDb>,
170    tx: Option<WriteTx>,
171    #[cfg(all(unix, not(target_os = "ios")))]
172    ipc: Option<&'a Ipc>,
173    budget_start: Option<Instant>,
174}
175
176/// Called while the guard is still held, so the panic report is written before any waiter,
177/// such as a UI thread about to blow its frame budget, can proceed. The process then exits,
178/// whichever thread held the lock, as a frame overrun on the UI thread does.
179fn check_hold(lock: &str, budget_start: Option<Instant>) {
180    let Some(start) = budget_start else { return };
181    let Some(budget) = lock_budget() else { return };
182    let held = start.elapsed();
183    if held > budget && !std::thread::panicking() {
184        let _ = std::panic::catch_unwind(|| lock_budget_destroyed(lock, held, budget));
185        std::process::exit(101);
186    }
187}
188
189impl Drop for LbRO<'_> {
190    fn drop(&mut self) {
191        check_hold("read", self.budget_start);
192    }
193}
194
195impl LbTx<'_> {
196    pub fn db(&mut self) -> &mut CoreV5 {
197        &mut self.guard.schema
198    }
199
200    pub fn end(mut self) {
201        self.flush().unwrap();
202    }
203
204    fn flush(&mut self) -> DbResult<()> {
205        let tx = self.tx.take().unwrap();
206        let seq_no = tx.seq_no;
207        let committed_seq = tx.end_tx(&mut *self.guard)?;
208        // Empty transactions retain the previous sequence, including after catch-up.
209        if committed_seq == seq_no {
210            #[cfg(all(unix, not(target_os = "ios")))]
211            if let Some(ipc) = self.ipc {
212                ipc.notify_peers();
213            }
214        }
215        Ok(())
216    }
217}
218
219impl Drop for LbTx<'_> {
220    fn drop(&mut self) {
221        if self.tx.is_some() {
222            if let Err(error) = self.flush() {
223                error!(?error, "failed to flush database transaction on drop");
224            }
225        }
226        check_hold("write", self.budget_start);
227    }
228}
229
230impl<S, D> Lb<S, D> {
231    pub async fn ro_tx(&self) -> LbRO<'_> {
232        let start = Instant::now();
233
234        let guard = self.db.read().await;
235
236        if start.elapsed() > Duration::from_millis(100) {
237            warn!("readonly transaction lock acquisition took {:?}", start.elapsed());
238        }
239
240        LbRO { guard, budget_start: self.budget_start() }
241    }
242
243    /// With [crate::model::core_config::Config::lock_budget], dev accounts exit when they release a lock held past
244    /// [lock_budget].
245    fn budget_start(&self) -> Option<Instant> {
246        let enforced = self.config.lock_budget && self.get_account().is_ok_and(Account::is_dev);
247        enforced.then(Instant::now)
248    }
249
250    /// note: you cannot call init for the same config, from the same tokio runtime, or you risk
251    /// deadlock. See the test `contended_transactions_do_not_block_the_runtime` for more info.
252    /// several workarounds exist for this situation that shouldn't really be required:
253    /// Lb is cheap to clone within the same runtime
254    /// Different data directories are fine
255    ///
256    /// If this situation actually becomes required:
257    ///
258    /// a config could be added to turn off file locks which is what results in tokio deadlocks, but
259    /// then what are you doing with multiple log writers writing to the same location?
260    ///
261    /// we could incur a small perf penalty and put the begin_tx in a tokio::blocking wrapper. This
262    /// is how tokio wants us to handle this, but I do not want the overhead.
263    pub async fn begin_tx(&self) -> LbTx<'_> {
264        let start = Instant::now();
265
266        let mut guard = self.db.write().await;
267
268        if start.elapsed() > Duration::from_millis(100) {
269            warn!("readwrite transaction lock acquisition took {:?}", start.elapsed());
270        }
271        let budget_start = self.budget_start();
272
273        let previous_seq = guard.last_modified();
274        let tx = guard.write_tx().unwrap();
275        if let Some(bytes) = guard.log_mut().take_incomplete_write() {
276            error!(bytes, "discarded an incomplete database write");
277        }
278        self.notify_catch_up(&guard.schema, previous_seq).await;
279
280        LbTx {
281            guard,
282            tx: Some(tx),
283            #[cfg(all(unix, not(target_os = "ios")))]
284            ipc: self.ipc.as_deref(),
285            budget_start,
286        }
287    }
288}