Skip to main content

lb_rs/service/
integrity.rs

1use crate::io::docs::LocalDocuments;
2use crate::io::server::Server;
3use std::num::NonZeroUsize;
4use std::thread;
5
6use futures::{StreamExt, stream};
7
8use crate::model::file_metadata::Owner;
9use crate::model::filename::DocumentType;
10use crate::model::tree_like::TreeLike;
11
12use crate::Lb;
13use crate::model::errors::{LbErrKind, LbResult, Warning};
14
15impl<S: Server, D: LocalDocuments> Lb<S, D> {
16    #[instrument(level = "debug", skip(self), err(Debug))]
17    pub async fn test_repo_integrity(&self, check_docs: bool) -> LbResult<Vec<Warning>> {
18        let tx = self.ro_tx().await;
19        let db = tx.db();
20
21        let mut tree = (&db.base_metadata).to_staged(&db.local_metadata).to_lazy();
22
23        if db.last_synced.as_ref().unwrap_or(&0) != &0 && db.root.as_ref().is_none() {
24            Err(LbErrKind::RootNonexistent)?;
25        }
26
27        tree.validate(Owner(self.keychain.get_pk()?))?;
28
29        for id in tree.ids() {
30            let name = tree.name(&id, &self.keychain)?;
31            if name.is_empty() {
32                Err(LbErrKind::FileNameEmpty)?; // todo: context candidate
33            }
34            if name.contains('/') {
35                Err(LbErrKind::FileNameContainsSlash)?; // todo: context candidate
36            }
37        }
38
39        drop(tx);
40
41        if !check_docs {
42            return Ok(vec![]);
43        }
44
45        let mut warnings = Vec::new();
46        let mut tasks = vec![];
47        for file in self.all_metadatas().await? {
48            if file.is_document() {
49                let is_text =
50                    DocumentType::from_file_name_using_extension(&file.name) == DocumentType::Text;
51
52                if is_text {
53                    tasks.push(async move { (file.id, self.read_document(file.id, false).await) });
54                }
55            }
56        }
57
58        let mut results = stream::iter(tasks).buffer_unordered(
59            thread::available_parallelism()
60                .unwrap_or(NonZeroUsize::new(4).unwrap())
61                .into(),
62        );
63
64        while let Some((id, res)) = results.next().await {
65            let doc = res?;
66            if doc.is_empty() {
67                warnings.push(Warning::EmptyFile(id));
68                continue;
69            }
70
71            if String::from_utf8(doc).is_err() {
72                warnings.push(Warning::InvalidUTF8(id));
73                continue;
74            }
75        }
76
77        Ok(warnings)
78    }
79}