Skip to main content

lb_rs/subscribers/
syncer.rs

1use crate::io::docs::LocalDocuments;
2use crate::io::server::Server;
3use std::{
4    collections::{HashMap, HashSet},
5    num::NonZeroUsize,
6    sync::Arc,
7    thread,
8    time::{Duration, Instant},
9};
10
11#[cfg(not(any(target_family = "wasm", target_os = "ios")))]
12use std::fs::{File, TryLockError};
13
14use futures::{StreamExt, stream};
15use tokio::sync::Mutex;
16#[cfg(not(target_family = "wasm"))]
17use tokio::sync::broadcast::error::{RecvError, TryRecvError};
18use tokio::time;
19use uuid::Uuid;
20
21use crate::{
22    Lb, LbErrKind, LbResult,
23    io::network::ApiError,
24    model::{
25        ValidationFailure,
26        access_info::UserAccessMode,
27        account::Account,
28        api::{
29            ChangeDocRequestV2, GetDocRequest, GetFileIdsRequest, GetUpdatesRequestV2,
30            GetUsernameError, GetUsernameRequest, UpsertDebugInfoRequest, UpsertRequestV2,
31        },
32        crypto::{AESKey, DecryptedDocument, EncryptedDocument},
33        errors::{LbErr, Unexpected},
34        file::ShareMode,
35        file_like::FileLike,
36        file_metadata::{DocumentHmac, FileDiff, FileType, Owner},
37        filename::{DocumentType, NameComponents},
38        lazy::LazyTree,
39        signed_meta::SignedMeta,
40        staged::StagedTreeLikeMut,
41        symkey,
42        tree_like::{TreeLike, TreeLikeMut},
43        validate,
44    },
45    service::events::{Actor, Event, SyncIncrement},
46};
47
48pub type Syncer = Arc<Mutex<SyncState>>;
49
50#[derive(Default)]
51pub struct SyncState {
52    /// the starting point for updates for this sync pass
53    last_synced: u64,
54
55    /// if our pull is successful, this is the timestamp we will commit
56    updates_as_of: u64,
57
58    /// changes we pulled from the server, post deduplication
59    remote_changes: Vec<SignedMeta>,
60
61    /// did we pull a root on this pass?
62    new_root: Option<Uuid>,
63
64    /// what docs did we pull as a result of this sync
65    pulled_docs: Vec<Uuid>,
66}
67
68// we are gonna have a fetch metadata fn which will get the docs that it needs to get, the ones
69// that match should_fetch
70//
71// should_fetch is going to be a tree fn that will return true if:
72//     is md or svg that descends from
73
74impl<S: Server, D: LocalDocuments> Lb<S, D> {
75    /// Outside iOS and WASM, returns `AlreadySyncing` if another instance is syncing this data directory.
76    #[instrument(level = "debug", skip(self), err(Debug))]
77    pub async fn sync(&self) -> LbResult<()> {
78        let mut sync_state = self.syncer.lock().await;
79        #[cfg(not(any(target_family = "wasm", target_os = "ios")))]
80        let _sync_lock = self.lock_sync()?;
81        self.events.sync_update(SyncIncrement::SyncStarted);
82
83        let pipeline: LbResult<()> = async {
84            self.pull_updates(&mut sync_state).await?;
85            self.push_local_changes().await?;
86            Ok(())
87        }
88        .await;
89
90        self.events.sync_update(SyncIncrement::SyncFinished(
91            pipeline.as_ref().err().map(|err| err.kind.clone()),
92        ));
93
94        self.cleanup().await?;
95
96        pipeline?;
97
98        let account = self.get_account()?.clone();
99
100        #[cfg(not(target_family = "wasm"))]
101        if account.is_beta() {
102            self.send_debug_info(account).await;
103        }
104
105        Ok(())
106    }
107
108    #[cfg(not(any(target_family = "wasm", target_os = "ios")))]
109    fn lock_sync(&self) -> LbResult<Option<File>> {
110        let Some(path) = &self.sync_lock else {
111            return Ok(None);
112        };
113        let file = File::options()
114            .read(true)
115            .write(true)
116            .create(true)
117            .truncate(false)
118            .open(path)?;
119        match file.try_lock() {
120            Ok(()) => Ok(Some(file)),
121            Err(TryLockError::WouldBlock) => Err(LbErrKind::AlreadySyncing.into()),
122            Err(TryLockError::Error(err)) => Err(err.into()),
123        }
124    }
125
126    pub(crate) async fn pull_updates(&self, sync_state: &mut SyncState) -> LbResult<()> {
127        self.inital_sync_state(sync_state).await?;
128        self.process_deletions().await?;
129        self.fetch_meta(sync_state).await?;
130        self.fetch_required_docs(sync_state).await?;
131        // todo: should this inform a re-pull?
132        self.merge(sync_state).await?;
133        self.commit_last_synced(sync_state).await?;
134        self.send_pull_events(sync_state).await?;
135
136        if !self.config.background_work {
137            self.populate_pk_cache().await?;
138        }
139
140        Ok(())
141    }
142
143    pub(crate) async fn push_local_changes(&self) -> LbResult<()> {
144        self.create_shared_attachments().await?;
145        self.push_meta().await?;
146        self.push_docs().await?;
147
148        Ok(())
149    }
150
151    /// For each note of mine that someone else can write, if it has no attachments folder, make one
152    async fn create_shared_attachments(&self) -> LbResult<()> {
153        if !self.attachments_folders {
154            return Ok(());
155        }
156        let me = Owner(self.keychain.get_pk()?);
157        let mut tx = self.begin_tx().await;
158        let db = tx.db();
159        let mut tree = (&db.base_metadata)
160            .to_staged(&mut db.local_metadata)
161            .to_lazy();
162        let mut ids = tree.ids();
163        ids.sort();
164        let mut created = false;
165        for id in ids {
166            if tree.wants_attachments(&id, me)? {
167                tree.create_attachments(
168                    self.entropy.id(),
169                    self.entropy.key(),
170                    &id,
171                    &self.keychain,
172                )?;
173                created = true;
174            }
175        }
176        tx.end();
177        if created {
178            self.events.meta_changed(Actor::Sync);
179        }
180        Ok(())
181    }
182
183    async fn inital_sync_state(&self, state: &mut SyncState) -> LbResult<()> {
184        // Catch up after acquiring the sync lock, before using the previous sync's cursor.
185        let mut tx = self.begin_tx().await;
186        let db = tx.db();
187
188        *state = Default::default();
189        state.last_synced = db.last_synced.as_ref().copied().unwrap_or_default() as u64;
190        tx.end();
191
192        Ok(())
193    }
194
195    pub(crate) async fn process_deletions(&self) -> LbResult<()> {
196        let server_ids = self
197            .client
198            .get_file_ids(self.get_account()?, GetFileIdsRequest {})
199            .await?
200            .ids;
201
202        let mut tx = self.begin_tx().await;
203        let db = tx.db();
204
205        let mut local = db.base_metadata.stage(&db.local_metadata).to_lazy();
206        let base_ids = local.tree.base.ids();
207
208        // files the server stopped listing and unlisted files whose existence is tied to them:
209        // their children and attachments
210        let mut prunable_ids: HashSet<Uuid> = base_ids
211            .into_iter()
212            .filter(|id| !server_ids.contains(id))
213            .collect();
214        let mut attached: HashMap<Uuid, Vec<Uuid>> = HashMap::new();
215        for id in local.ids() {
216            if let Some(of) = local.find(&id)?.attachment_of() {
217                attached.entry(of.id).or_default().push(id);
218            }
219        }
220        let mut to_visit: Vec<Uuid> = prunable_ids.iter().copied().collect();
221        while let Some(id) = to_visit.pop() {
222            let mut under = Vec::new();
223            for child in local.children(&id)? {
224                // concurrent edits can leave an attachments folder looking like it should be pruned
225                // without an exception for when its document is not
226                let follows_document = local
227                    .find(&child)?
228                    .attachment_of()
229                    .is_some_and(|of| server_ids.contains(&of.id));
230                if !follows_document {
231                    under.push(child);
232                }
233            }
234            under.extend(attached.get(&id).into_iter().flatten().copied());
235            for child in under {
236                if !server_ids.contains(&child) && prunable_ids.insert(child) {
237                    to_visit.push(child);
238                }
239            }
240        }
241
242        // a file the server still has keeps its other changes: a pending move into a pruned
243        // folder is undone
244        let mut moved_in = Vec::new();
245        for id in db.local_metadata.ids() {
246            let parent = *local.find(&id)?.parent();
247            if let Some(base_file) = local.tree.base.maybe_find(&id) {
248                if prunable_ids.contains(&parent)
249                    && !prunable_ids.contains(&id)
250                    && !prunable_ids.contains(base_file.parent())
251                {
252                    moved_in.push((id, *base_file.parent()));
253                }
254            }
255        }
256        for id in &prunable_ids {
257            if let Some(&hmac) = local
258                .tree
259                .base
260                .maybe_find(id)
261                .and_then(|f| f.document_hmac())
262            {
263                self.docs.delete(*id, hmac).await?;
264            }
265            if let Some(&hmac) = local.maybe_find(id).and_then(|f| f.document_hmac()) {
266                self.docs.delete(*id, hmac).await?;
267            }
268        }
269
270        let mut tree = (&db.base_metadata)
271            .to_staged(&mut db.local_metadata)
272            .to_lazy();
273        for (id, parent) in moved_in {
274            tree.move_unvalidated(&id, &parent, &self.keychain)?;
275        }
276
277        let mut base_staged = (&mut db.base_metadata).to_lazy().stage(None);
278        base_staged.tree.removed = prunable_ids.iter().copied().collect();
279        base_staged.promote()?;
280
281        let mut local_staged = (&mut db.local_metadata).to_lazy().stage(None);
282        local_staged.tree.removed = prunable_ids.iter().copied().collect();
283        local_staged.promote()?;
284
285        if !prunable_ids.is_empty() {
286            self.events.meta_changed(Actor::Sync);
287        }
288
289        Ok(())
290    }
291
292    async fn fetch_meta(&self, state: &mut SyncState) -> LbResult<()> {
293        let updates = self
294            .client
295            .get_updates_v2(
296                self.get_account()?,
297                GetUpdatesRequestV2 { since_metadata_version: state.last_synced },
298            )
299            .await?;
300
301        let tx = self.ro_tx().await;
302        let db = tx.db();
303
304        // this loop implicitly prunes remote orphans; like validation, a deleted file whose
305        // parent left the tree is not one
306        let mut without_orphans = Vec::new();
307        let me = Owner(self.keychain.get_pk()?);
308        let remote = db.base_metadata.stage(updates.file_metadata).to_lazy();
309        for id in remote.tree.staged.ids() {
310            let meta = remote.find(&id)?;
311            if remote.maybe_find_parent(meta).is_some()
312                || remote.maybe_find_attached(meta).is_some()
313                || meta.explicitly_deleted()
314                || meta
315                    .user_access_keys()
316                    .iter()
317                    .any(|k| k.encrypted_for == me.0)
318            {
319                without_orphans.push(remote.find(&id)?.clone());
320            }
321        }
322
323        // this is what actually performs the deduplication
324        let pruned_tree = db.base_metadata.stage(without_orphans).pruned()?.to_lazy();
325        let (_, deduped_changes) = pruned_tree.unstage();
326
327        // initialize root if this is the first pull on this device
328        let mut root_id = None;
329        if db.root.as_ref().is_none() {
330            let root = deduped_changes
331                .all_files()?
332                .into_iter()
333                .find(|f| f.is_root())
334                .ok_or(LbErrKind::RootNonexistent)?;
335            root_id = Some(*root.id());
336        }
337
338        state.remote_changes = deduped_changes;
339        state.updates_as_of = updates.as_of_metadata_version;
340        state.new_root = root_id;
341
342        Ok(())
343    }
344
345    async fn fetch_required_docs(&self, state: &mut SyncState) -> LbResult<()> {
346        let mut docs_to_pull = vec![];
347
348        let tx = self.ro_tx().await;
349        let db = tx.db();
350
351        let mut files_with_local_edits = vec![];
352        let local = db.base_metadata.stage(&db.local_metadata);
353        for id in local.staged.ids() {
354            if let Some(base) = local.base.maybe_find(&id) {
355                if let Some(local_hmac) = local.find(&id)?.document_hmac() {
356                    if Some(local_hmac) != base.document_hmac() {
357                        files_with_local_edits.push(id);
358                    }
359                }
360            }
361        }
362
363        let mut remote = db
364            .base_metadata
365            .stage(state.remote_changes.clone())
366            .to_lazy();
367
368        for id in remote.tree.staged.ids() {
369            if remote.calculate_deleted(&id)? {
370                continue;
371            }
372            let remote_hmac = remote.find(&id)?.document_hmac().cloned();
373            let base_hmac = remote
374                .tree
375                .base
376                .maybe_find(&id)
377                .and_then(|f| f.document_hmac())
378                .cloned();
379            if base_hmac == remote_hmac {
380                continue;
381            }
382
383            if let Some(remote_hmac) = remote_hmac {
384                // pull a file if we have a prior base, this is our heuristic -- do they have the
385                // ability to edit this file while we release the lock and are pulling all the
386                // files
387                if base_hmac.is_some_and(|base_hmac| self.docs.exists(id, base_hmac))
388                    && !self.docs.exists(id, remote_hmac)
389                {
390                    docs_to_pull.push((id, remote_hmac));
391                }
392
393                // this clause captures documents which went from being new -> multiple parties
394                // having updates. We'll still need the updates
395                if files_with_local_edits.contains(&id)
396                    && !docs_to_pull
397                        .iter()
398                        .any(|(already_pulling, _)| already_pulling == &id)
399                {
400                    if let Some(base_hmac) = base_hmac {
401                        if !self.docs.exists(id, base_hmac) {
402                            // this scenario basically only comes up in tests
403                            // someone modifies a file directly without reading the prior version
404                            docs_to_pull.push((id, base_hmac));
405                        }
406                    }
407                    docs_to_pull.push((id, remote_hmac));
408                }
409            }
410        }
411        drop(tx);
412
413        let futures = docs_to_pull
414            .into_iter()
415            .map(|(id, hmac)| async move { self.ensure_doc_available(id, hmac).await.map(|_| id) });
416
417        let mut stream = stream::iter(futures).buffer_unordered(
418            thread::available_parallelism()
419                .unwrap_or(NonZeroUsize::new(4).unwrap())
420                .into(),
421        );
422
423        while let Some(fut) = stream.next().await {
424            let id = fut?;
425            state.pulled_docs.push(id);
426        }
427
428        Ok(())
429    }
430
431    pub(crate) async fn ensure_doc_available(
432        &self, id: Uuid, hmac: DocumentHmac,
433    ) -> LbResult<Option<EncryptedDocument>> {
434        // todo: in a lot of cases there is a list of ids we're trying to get, it would be better
435        // if the caller managed the event updates, the status would be more meaningful for longer
436
437        // in this world, can we get stuck pushing a doc as well? Probably fine for now
438        if self.docs.exists(id, hmac) {
439            return Ok(None);
440        }
441
442        self.events
443            .sync_update(SyncIncrement::PullingDocument(id, true));
444        let remote_document = self
445            .client
446            .get_document(self.get_account()?, GetDocRequest { id, hmac })
447            .await?;
448        self.docs.insert(id, hmac, &remote_document.content).await?;
449        self.events
450            .sync_update(SyncIncrement::PullingDocument(id, false));
451
452        Ok(Some(remote_document.content))
453    }
454
455    pub(crate) async fn fetch_doc(
456        &self, id: Uuid, hmac: DocumentHmac,
457    ) -> LbResult<EncryptedDocument> {
458        match self.ensure_doc_available(id, hmac).await? {
459            Some(doc) => Ok(doc),
460            None => self.docs.get(id, hmac).await,
461        }
462    }
463
464    /// Pulls remote changes and constructs a changeset Merge such that Stage<Stage<Stage<Base, Remote>, Local>, Merge> is valid.
465    /// Promotes Base to Stage<Base, Remote> and Local to Stage<Local, Merge>
466    async fn merge(&self, state: &mut SyncState) -> LbResult<()> {
467        let mut tx = self.begin_tx().await;
468        let db = tx.db();
469        let start = Instant::now();
470
471        let remote_changes = &state.remote_changes;
472
473        // fetch document updates and local documents for merge
474        let me = Owner(self.keychain.get_pk()?);
475
476        // compute merge changes
477        let merge_changes = {
478            // assemble trees
479            let mut base = (&db.base_metadata).to_lazy();
480            let remote_unlazy = (&db.base_metadata).to_staged(remote_changes);
481            let mut remote = remote_unlazy.as_lazy();
482            let mut local = (&db.base_metadata).to_staged(&db.local_metadata).to_lazy();
483
484            // changeset constraints - these evolve as we try to assemble changes and encounter validation failures
485            let mut files_to_unmove: HashSet<Uuid> = HashSet::new();
486            let mut files_to_unshare: HashSet<Uuid> = HashSet::new();
487            let mut links_to_delete: HashSet<Uuid> = HashSet::new();
488            // folders this device created that sync replaces with one the server already has; the
489            // contents go in the replacement
490            let mut replaced_folders: HashMap<Uuid, Uuid> = HashMap::new();
491            let mut rename_increments: HashMap<Uuid, usize> = HashMap::new();
492            // Id and key share one lifetime: the merge, including construction retries.
493            // A new key per attempt encrypts with the key cached by the failed attempt.
494            let mut duplicate_file_ids: HashMap<Uuid, (Uuid, AESKey)> = HashMap::new();
495
496            'merge_construction: loop {
497                // judged afresh each attempt, since an undone cycle can change a destination's access
498                let mut refused_moves: HashSet<Uuid> = HashSet::new();
499                // process just the edits which allow us to check deletions in the result
500                let mut remote_with_moves = {
501                    let mut remote_with_moves = remote_unlazy.stage(Vec::new()).to_lazy();
502
503                    // creations
504                    let mut deletion_creations = HashSet::new();
505                    for id in db.local_metadata.ids() {
506                        if remote.maybe_find(&id).is_none()
507                            && !links_to_delete.contains(&id)
508                            && !replaced_folders.contains_key(&id)
509                        {
510                            deletion_creations.insert(id);
511                        }
512                    }
513                    for id in parents_first(&local, &deletion_creations)? {
514                        let local_file = local.find(&id)?.clone();
515                        let parent =
516                            created_parent(&remote_with_moves, &local_file, &replaced_folders);
517                        remote_with_moves
518                            .create_unvalidated(
519                                id,
520                                symkey::generate_key(),
521                                &parent,
522                                &local.name(&id, &self.keychain)?,
523                                local_file.file_type(),
524                                local_file.attachment_of().cloned(),
525                                &self.keychain,
526                            )
527                            .map_err(orphaned_creation(id))?;
528                    }
529
530                    // moves (creations happen first in case a file is moved into a new folder);
531                    // as in the merge, skipping files the server moved or deleted; parents first,
532                    // so a destination is judged where its own kept move puts it
533                    let local_ids = db.local_metadata.ids().into_iter().collect();
534                    for id in parents_first(&local, &local_ids)? {
535                        let local_file = local.find(&id)?.clone();
536                        if let Some(base_file) = db.base_metadata.maybe_find(&id).cloned() {
537                            if !local_file.explicitly_deleted()
538                                && local_file.parent() != base_file.parent()
539                                && remote.find(&id)?.parent() == base_file.parent()
540                                && !remote.calculate_deleted(&id)?
541                                && !files_to_unmove.contains(&id)
542                            {
543                                // a move this device may no longer make is undone; at the source
544                                // only the server's grant counts, since leaving a share after
545                                // moving out of it is this device's own later change
546                                let from = remote.find(&id)?.parent();
547                                let may_move_from = remote.maybe_find(from).is_some()
548                                    && remote.access_mode(me, from)? >= Some(UserAccessMode::Write);
549                                let to = replacement(&replaced_folders, local_file.parent());
550                                if !may_move_from
551                                    || !may_write_in(&local, &remote_with_moves, me, &to)?
552                                {
553                                    refused_moves.insert(id);
554                                    continue;
555                                }
556                                // move
557                                remote_with_moves.move_unvalidated(&id, &to, &self.keychain)?;
558                            }
559                        }
560                    }
561
562                    // deletions (moves happen first in case a file is moved into a deleted folder)
563                    for id in db.local_metadata.ids() {
564                        let local_file = local.find(&id)?.clone();
565                        let parent = *remote.maybe_find(&id).unwrap_or(&local_file).parent();
566                        if local_file.explicitly_deleted()
567                            && !lost_access(&local, &remote, me, &id)?
568                            && may_write_in(&local, &remote, me, &parent)?
569                        {
570                            // delete
571                            remote_with_moves.delete_unvalidated(&id, &self.keychain)?;
572                        }
573                    }
574                    remote_with_moves
575                };
576
577                // process all edits, dropping non-deletion edits for files that will be implicitly deleted
578                let mut merge = {
579                    let mut merge = remote_unlazy.stage(Vec::new()).to_lazy();
580
581                    // creations and edits of created documents
582                    let mut creations = HashSet::new();
583                    for id in db.local_metadata.ids() {
584                        if remote_with_moves.maybe_find(&id).is_some()
585                            && !remote_with_moves.calculate_deleted(&id)?
586                            && remote.maybe_find(&id).is_none()
587                            && !links_to_delete.contains(&id)
588                            && !lost_access(&local, &remote, me, &id)?
589                            && may_write_in(
590                                &local,
591                                &remote_with_moves,
592                                me,
593                                &created_parent(
594                                    &remote_with_moves,
595                                    local.find(&id)?,
596                                    &replaced_folders,
597                                ),
598                            )?
599                        {
600                            creations.insert(id);
601                        }
602                    }
603                    for id in parents_first(&local, &creations)? {
604                        let local_file = local.find(&id)?.clone();
605                        let parent = created_parent(&merge, &local_file, &replaced_folders);
606                        merge
607                            .create_unvalidated(
608                                id,
609                                local.decrypt_key(&id, &self.keychain)?,
610                                &parent,
611                                &local.name(&id, &self.keychain)?,
612                                local_file.file_type(),
613                                local_file.attachment_of().cloned(),
614                                &self.keychain,
615                            )
616                            .map_err(orphaned_creation(id))?;
617                    }
618
619                    // deletes
620                    // before moves, so a moved folder leaves the files this device deleted as they
621                    // were; a file is deleted itself unless its parent is deleted and holds it in
622                    // the merge too, since moves skip deleted files but may lift live ones
623                    for id in db.local_metadata.ids() {
624                        if db.base_metadata.maybe_find(&id).is_none()
625                            || !remote_with_moves.calculate_deleted(&id)?
626                            || remote.calculate_deleted(&id)?
627                        {
628                            continue;
629                        }
630                        let deleted = remote_with_moves.find(&id)?;
631                        if deleted.explicitly_deleted()
632                            || deleted.parent() != merge.find(&id)?.parent()
633                        {
634                            // delete
635                            merge.delete_unvalidated(&id, &self.keychain)?;
636                        }
637                    }
638                    for &id in &links_to_delete {
639                        // delete
640                        if merge.maybe_find(&id).is_some()
641                            && !merge.find(&id)?.explicitly_deleted()
642                            && !(remote.maybe_find(&id).is_some()
643                                && remote.calculate_deleted(&id)?)
644                        {
645                            merge.delete_unvalidated(&id, &self.keychain)?;
646                        }
647                    }
648
649                    // skip files that are already deleted, will be deleted, were not created, or
650                    // are no longer reachable from this device
651                    let mut replayed = Vec::new();
652                    for id in db.local_metadata.ids() {
653                        if merge.maybe_find(&id).is_some()
654                            && remote_with_moves.maybe_find(&id).is_some()
655                            && !remote_with_moves.calculate_deleted(&id)?
656                            && !(remote.maybe_find(&id).is_some()
657                                && remote.calculate_deleted(&id)?)
658                            && !links_to_delete.contains(&id)
659                            && !lost_access(&local, &remote, me, &id)?
660                        {
661                            replayed.push(id);
662                        }
663                    }
664
665                    // moves (creations happen first in case a file is moved into a new folder)
666                    for &id in &replayed {
667                        let local_file = local.find(&id)?;
668                        if let Some(base_file) = base.maybe_find(&id) {
669                            if local_file.parent() != base_file.parent()
670                                && remote.find(&id)?.parent() == base_file.parent()
671                                && !files_to_unmove.contains(&id)
672                                && !refused_moves.contains(&id)
673                            {
674                                let parent = replacement(&replaced_folders, local_file.parent());
675                                merge.move_unvalidated(&id, &parent, &self.keychain)?;
676                            }
677                        }
678                    }
679                    // access is read from the merge below, which needs a tree without cycles; the
680                    // full validation after construction reports every other failure
681                    if let Err(LbErr {
682                        kind: LbErrKind::Validation(ValidationFailure::Cycle(ids)),
683                        ..
684                    }) = merge.assert_no_cycles()
685                    {
686                        unmove_cycle(&local, &db.local_metadata, &ids, &mut files_to_unmove)?;
687                        continue 'merge_construction;
688                    }
689
690                    // renames, edits, and shares (moves happen first so each file is where
691                    // the merge puts it)
692                    for id in replayed {
693                        let local_file = local.find(&id)?.clone();
694                        let local_name = local.name(&id, &self.keychain)?;
695                        let maybe_base_file = base.maybe_find(&id).cloned();
696                        let maybe_remote_file = remote.maybe_find(&id).cloned();
697                        if maybe_base_file.is_some() {
698                            let base_name = base.name(&id, &self.keychain)?;
699                            let remote_name = remote.name(&id, &self.keychain)?;
700
701                            // rename
702                            if local_name != base_name
703                                && remote_name == base_name
704                                && may_write_in(
705                                    &local,
706                                    &remote_with_moves,
707                                    me,
708                                    merge.find(&id)?.parent(),
709                                )?
710                            {
711                                merge.rename_unvalidated(&id, &local_name, &self.keychain)?;
712                            }
713                        }
714
715                        // share: replay what this device changed about each recipient's share;
716                        // when the server changed it too, this device wins if either side unshared,
717                        // otherwise the higher mode
718                        let writable = may_write_in(&local, &remote_with_moves, me, &id)?;
719                        let base_keys = shares_by_recipient(maybe_base_file.as_ref());
720                        let remote_keys = shares_by_recipient(maybe_remote_file.as_ref());
721                        let owner = merge.find(&id)?.owner();
722                        // in the file's order, so shares keep the order they were added in; a
723                        // recipient's last key is its share, as in shares_by_recipient
724                        let keys = local_file.user_access_keys();
725                        for (i, key) in keys.iter().enumerate() {
726                            if keys[i + 1..]
727                                .iter()
728                                .any(|k| k.encrypted_for == key.encrypted_for)
729                            {
730                                continue;
731                            }
732                            let (for_, local) = (Owner(key.encrypted_for), (key.mode, key.deleted));
733                            let base = base_keys.get(&for_).copied();
734                            // a move may have made the recipient the owner, whose share only an
735                            // unshare changes
736                            if Some(local) == base || (for_ == owner && !local.1) {
737                                continue;
738                            }
739                            let remote = remote_keys.get(&for_).copied();
740                            let remote_live = remote.filter(|&(_, deleted)| !deleted);
741                            let (mode, deleted) = local;
742                            if deleted {
743                                let mine = for_ == me;
744                                if remote_live.is_some() && (mine || writable) {
745                                    merge.delete_share_unvalidated(
746                                        &id,
747                                        Some(for_.0),
748                                        &self.keychain,
749                                    )?;
750                                }
751                                continue;
752                            }
753                            let wins = remote == base
754                                || remote_live.is_none_or(|(remote_mode, _)| mode > remote_mode);
755                            let mode = match mode {
756                                UserAccessMode::Read => ShareMode::Read,
757                                UserAccessMode::Write => ShareMode::Write,
758                                UserAccessMode::Owner => continue,
759                            };
760                            if wins && writable {
761                                merge.add_share_unvalidated(id, for_, mode, &self.keychain)?;
762                            }
763                        }
764                        // share deletion due to conflicts
765                        if files_to_unshare.contains(&id) {
766                            merge.delete_share_unvalidated(&id, None, &self.keychain)?;
767                        }
768
769                        // rename due to path conflict
770                        if let Some(&rename_increment) = rename_increments.get(&id) {
771                            let name = if local_file.is_folder() {
772                                NameComponents::folder(&local_name)
773                            } else {
774                                NameComponents::from(&local_name)
775                            };
776                            let name = name.numbered(rename_increment + 1);
777                            merge.rename_unvalidated(&id, &name, &self.keychain)?;
778                        }
779
780                        // edit
781                        let base_hmac = maybe_base_file.and_then(|f| f.document_hmac().cloned());
782                        let remote_hmac =
783                            maybe_remote_file.and_then(|f| f.document_hmac().cloned());
784                        let local_hmac = local_file.document_hmac().cloned();
785                        if may_write_in(&local, &remote_with_moves, me, &id)?
786                            && local_hmac != base_hmac
787                        {
788                            if remote_hmac != base_hmac && remote_hmac != local_hmac {
789                                // merge
790                                let merge_name = merge.name(&id, &self.keychain)?;
791                                let document_type =
792                                    DocumentType::from_file_name_using_extension(&merge_name);
793
794                                // todo these accesses are potentially problematic
795                                // maybe not if service/docs is the persion doing network io
796                                let base_document =
797                                    self.read_document_helper(id, &mut base).await?;
798                                let remote_document =
799                                    self.read_document_helper(id, &mut remote).await?;
800                                let local_document =
801                                    self.read_document_helper(id, &mut local).await?;
802
803                                match document_type.merge(
804                                    &base_document,
805                                    &local_document,
806                                    &remote_document,
807                                ) {
808                                    Some(merged_document) => {
809                                        let encrypted_document = merge
810                                            .update_document_unvalidated(
811                                                &id,
812                                                &merged_document,
813                                                &self.keychain,
814                                            )?;
815                                        if let Some(&hmac) = merge.find(&id)?.document_hmac() {
816                                            self.docs.insert(id, hmac, &encrypted_document).await?;
817                                        }
818                                    }
819                                    None => {
820                                        // duplicate file, in the document's folder if this device
821                                        // may write there, otherwise beside its link; with no
822                                        // link there's nowhere to put it
823                                        let parent = *merge.find(&id)?.parent();
824                                        let writable = merge.maybe_find(&parent).is_some()
825                                            && may_write_in(
826                                                &local,
827                                                &remote_with_moves,
828                                                me,
829                                                &parent,
830                                            )?;
831                                        let copy_parent = if writable {
832                                            Some(parent)
833                                        } else if let Some(link) = merge.linked_by(&id)? {
834                                            Some(*merge.find(&link)?.parent())
835                                        } else {
836                                            None
837                                        };
838                                        if let Some(merge_parent) = copy_parent {
839                                            let (duplicate_id, duplicate_key) =
840                                                if let Some(&tracked) = duplicate_file_ids.get(&id)
841                                                {
842                                                    tracked
843                                                } else {
844                                                    let duplicate_id = self.entropy.id();
845                                                    let duplicate_key = self.entropy.key();
846                                                    duplicate_file_ids
847                                                        .insert(id, (duplicate_id, duplicate_key));
848                                                    rename_increments.insert(duplicate_id, 1);
849                                                    (duplicate_id, duplicate_key)
850                                                };
851
852                                            let merge_name = NameComponents::from(&merge_name)
853                                                .copy(rename_increments[&duplicate_id]);
854
855                                            merge.create_unvalidated(
856                                                duplicate_id,
857                                                duplicate_key,
858                                                &merge_parent,
859                                                &merge_name,
860                                                FileType::Document,
861                                                None,
862                                                &self.keychain,
863                                            )?;
864                                            let encrypted_document = merge
865                                                .update_document_unvalidated(
866                                                    &duplicate_id,
867                                                    &local_document,
868                                                    &self.keychain,
869                                                )?;
870                                            if let Some(&duplicate_hmac) =
871                                                merge.find(&duplicate_id)?.document_hmac()
872                                            {
873                                                self.docs
874                                                    .insert(
875                                                        duplicate_id,
876                                                        duplicate_hmac,
877                                                        &encrypted_document,
878                                                    )
879                                                    .await?;
880                                            }
881                                        }
882                                    }
883                                }
884                            } else {
885                                let local_file = local.find(&id)?;
886                                merge.overwrite_document_hmac_unvalidated(
887                                    &id,
888                                    local_file.document_hmac().copied(),
889                                    local_file.doc_size(),
890                                    &self.keychain,
891                                )?;
892                            }
893                        }
894                    }
895
896                    // repair: each attachments folder goes beside its document, keeping its name;
897                    // documents in id order so every device repairs a tree the same way
898                    let mut attached = Vec::new();
899                    for id in merge.ids() {
900                        if let Some(of) = merge.find(&id)?.attachment_of() {
901                            attached.push((of.id, id));
902                        }
903                    }
904                    attached.sort();
905                    for (document, folder) in attached {
906                        if merge.maybe_find(&document).is_none()
907                            || merge.calculate_deleted(&document)?
908                            || merge.calculate_deleted(&folder)?
909                        {
910                            continue;
911                        }
912                        let parent = *merge.find(&document)?.parent();
913                        let folder_parent = *merge.find(&folder)?.parent();
914                        if parent != folder_parent
915                            && may_write_in(&local, &remote_with_moves, me, &parent)?
916                            && may_write_in(&local, &remote_with_moves, me, &folder_parent)?
917                        {
918                            merge.move_attachments_beside_note(
919                                &document,
920                                &folder,
921                                &self.keychain,
922                            )?;
923                        }
924                    }
925
926                    merge
927                };
928
929                // validate; handle failures by introducing changeset constraints
930                for link in merge.ids() {
931                    if !merge.calculate_deleted(&link)? {
932                        if let FileType::Link { target } = merge.find(&link)?.file_type() {
933                            if merge.maybe_find(&target).is_some()
934                                && merge.calculate_deleted(&target)?
935                            {
936                                // delete links to deleted files
937                                if links_to_delete.insert(link) {
938                                    continue 'merge_construction;
939                                } else {
940                                    return Err(LbErrKind::Unexpected(format!(
941                                        "sync failed to resolve broken link (deletion): {link:?}"
942                                    ))
943                                    .into());
944                                }
945                            }
946                        }
947                    }
948                }
949
950                let validate_result = merge.validate(me);
951                match validate_result {
952                    // merge changeset is valid
953                    Ok(_) => {
954                        let (_, merge_changes) = merge.unstage();
955                        break merge_changes;
956                    }
957                    Err(ref err) => match err.kind {
958                        LbErrKind::Validation(ref vf) => match vf {
959                            // merge changeset has resolvable validation errors and needs modification
960                            ValidationFailure::Cycle(ids) => {
961                                unmove_cycle(
962                                    &local,
963                                    &db.local_metadata,
964                                    ids,
965                                    &mut files_to_unmove,
966                                )?;
967                            }
968                            ValidationFailure::PathConflict(ids) => {
969                                // pick one local id and generate a non-conflicting filename
970                                let mut progress = false;
971                                for &id in ids {
972                                    if duplicate_file_ids.values().any(|&(dup, _)| dup == id) {
973                                        *rename_increments.entry(id).or_insert(0) += 1;
974                                        progress = true;
975                                        break;
976                                    }
977                                }
978                                if !progress {
979                                    for &id in ids {
980                                        if db.local_metadata.maybe_find(&id).is_some() {
981                                            *rename_increments.entry(id).or_insert(0) += 1;
982                                            progress = true;
983                                            break;
984                                        }
985                                    }
986                                }
987                                if !progress {
988                                    return Err(LbErrKind::Unexpected(format!(
989                                        "sync failed to resolve path conflict: {ids:?}"
990                                    ))
991                                    .into());
992                                }
993                            }
994                            ValidationFailure::SharedLink { link, shared_ancestor } => {
995                                // if ancestor is newly shared, delete share; if this device moved
996                                // the link, or a folder between it and the share, into the share,
997                                // undo that move unless it would land in a deleted folder;
998                                // otherwise delete link
999                                let mut progress = false;
1000                                if let Some(base_shared_ancestor) = base.maybe_find(shared_ancestor)
1001                                {
1002                                    if !base_shared_ancestor.is_shared()
1003                                        && files_to_unshare.insert(*shared_ancestor)
1004                                    {
1005                                        progress = true;
1006                                    }
1007                                }
1008                                let mut id = *link;
1009                                while !progress && id != *shared_ancestor {
1010                                    if let (Some(base_file), Some(remote_file)) =
1011                                        (base.maybe_find(&id), remote.maybe_find(&id))
1012                                    {
1013                                        let from = *remote_file.parent();
1014                                        let moved_here =
1015                                            db.local_metadata.maybe_find(&id).is_some()
1016                                                && local.find(&id)?.parent() != base_file.parent()
1017                                                && from == *base_file.parent();
1018                                        if moved_here
1019                                            && !remote_with_moves.calculate_deleted(&from)?
1020                                            && files_to_unmove.insert(id)
1021                                        {
1022                                            progress = true;
1023                                        }
1024                                    }
1025                                    id = *merge.find(&id)?.parent();
1026                                }
1027                                if !progress && links_to_delete.insert(*link) {
1028                                    progress = true;
1029                                }
1030                                if !progress {
1031                                    return Err(LbErrKind::Unexpected(format!(
1032                                    "sync failed to resolve shared link: link: {link:?}, shared_ancestor: {shared_ancestor:?}"
1033                                )).into());
1034                                }
1035                            }
1036                            ValidationFailure::DuplicateLink { target } => {
1037                                // delete local link with this target
1038                                let mut progress = false;
1039                                if let Some(link) = local.linked_by(target)? {
1040                                    if links_to_delete.insert(link) {
1041                                        progress = true;
1042                                    }
1043                                }
1044                                if !progress {
1045                                    return Err(LbErrKind::Unexpected(format!(
1046                                        "sync failed to resolve duplicate link: target: {target:?}"
1047                                    ))
1048                                    .into());
1049                                }
1050                            }
1051                            ValidationFailure::BrokenLink(link) => {
1052                                // delete local link with this target
1053                                if !links_to_delete.insert(*link) {
1054                                    return Err(LbErrKind::Unexpected(format!(
1055                                        "sync failed to resolve broken link: {link:?}"
1056                                    ))
1057                                    .into());
1058                                }
1059                            }
1060                            ValidationFailure::OwnedLink(link) => {
1061                                // if target is newly owned, unmove target, otherwise delete link
1062                                let mut progress = false;
1063                                if let Some(remote_link) = remote.maybe_find(link) {
1064                                    if let FileType::Link { target } = remote_link.file_type() {
1065                                        let remote_target = remote.find(&target)?;
1066                                        if remote_target.owner() != me
1067                                            && files_to_unmove.insert(target)
1068                                        {
1069                                            progress = true;
1070                                        }
1071                                    }
1072                                }
1073                                if !progress && links_to_delete.insert(*link) {
1074                                    progress = true;
1075                                }
1076                                if !progress {
1077                                    return Err(LbErrKind::Unexpected(format!(
1078                                        "sync failed to resolve owned link: {link:?}"
1079                                    ))
1080                                    .into());
1081                                }
1082                            }
1083                            ValidationFailure::DuplicateAttachmentsFolder { document } => {
1084                                // the server's folder stays; this device's new one is replaced by
1085                                // it
1086                                let mut existing = None;
1087                                let mut new = None;
1088                                for id in merge.ids() {
1089                                    let file = merge.find(&id)?;
1090                                    if file.attachment_of().map(|of| of.id) != Some(*document)
1091                                        || merge.calculate_deleted(&id)?
1092                                    {
1093                                        continue;
1094                                    }
1095                                    if remote.maybe_find(&id).is_some() {
1096                                        existing = Some(id);
1097                                    } else {
1098                                        new = Some(id);
1099                                    }
1100                                }
1101                                let progress = match (existing, new) {
1102                                    (Some(existing), Some(new)) => {
1103                                        replaced_folders.insert(new, existing).is_none()
1104                                    }
1105                                    _ => false,
1106                                };
1107                                if !progress {
1108                                    return Err(LbErrKind::Unexpected(format!(
1109                                        "sync failed to resolve duplicate attachments folders: document: {document:?}"
1110                                    ))
1111                                    .into());
1112                                }
1113                            }
1114                            // merge changeset has unexpected validation errors
1115                            ValidationFailure::Orphan(_)
1116                            | ValidationFailure::NonFolderWithChildren(_)
1117                            | ValidationFailure::FileWithDifferentOwnerParent(_)
1118                            | ValidationFailure::FileNameTooLong(_)
1119                            | ValidationFailure::DeletedFileUpdated(_)
1120                            | ValidationFailure::NonDecryptableFileName(_)
1121                            | ValidationFailure::SelfShare(_)
1122                            | ValidationFailure::InvalidAttachmentsFolder(_)
1123                            | ValidationFailure::MisplacedAttachmentsFolder(_) => {
1124                                validate_result?;
1125                            }
1126                        },
1127                        // merge changeset has unexpected errors
1128                        _ => {
1129                            validate_result?;
1130                        }
1131                    },
1132                }
1133            }
1134        };
1135
1136        // base = remote; local = merge
1137        (&mut db.base_metadata)
1138            .to_staged(remote_changes.clone())
1139            .to_lazy()
1140            .promote()?;
1141        db.local_metadata.clear()?;
1142        (&mut db.local_metadata)
1143            .to_staged(merge_changes)
1144            .to_lazy()
1145            .promote()?;
1146
1147        // todo who else calls this did they manage locks right?
1148        // self.cleanup_local_metadata()?;
1149        db.base_metadata.stage(&mut db.local_metadata).prune()?;
1150
1151        if start.elapsed() > web_time::Duration::from_millis(100) {
1152            warn!("sync merge held lock for {:?}", start.elapsed());
1153        }
1154
1155        Ok(())
1156    }
1157
1158    async fn send_pull_events(&self, state: &mut SyncState) -> LbResult<()> {
1159        if state.new_root.is_some() {
1160            self.events.signed_in();
1161        }
1162
1163        if !state.remote_changes.is_empty() {
1164            self.events.meta_changed(Actor::Sync);
1165
1166            let owner = Owner(self.keychain.get_pk()?);
1167            if state.remote_changes.iter().any(|f| f.owner() != owner) {
1168                self.events.pending_shares_changed();
1169            }
1170        }
1171
1172        for &doc in &state.pulled_docs {
1173            self.events.doc_written(doc, Actor::Sync);
1174        }
1175
1176        Ok(())
1177    }
1178
1179    async fn commit_last_synced(&self, state: &mut SyncState) -> LbResult<()> {
1180        let mut tx = self.begin_tx().await;
1181        let db = tx.db();
1182        db.last_synced.replace(state.updates_as_of as i64)?;
1183
1184        if let Some(root) = state.new_root {
1185            db.root.replace(root)?;
1186        }
1187
1188        Ok(())
1189    }
1190
1191    async fn populate_pk_cache(&self) -> LbResult<()> {
1192        // todo: is this the move?
1193        let mut missing_owners = HashSet::new();
1194        {
1195            let tx = self.ro_tx().await;
1196            let db = tx.db();
1197            for file in db.base_metadata.iter().map(|(_, value)| value) {
1198                for user_access_key in file.user_access_keys() {
1199                    let enc_by = Owner(user_access_key.encrypted_by);
1200                    let enc_for = Owner(user_access_key.encrypted_for);
1201
1202                    if !db.pub_key_lookup.contains_key(&enc_by) {
1203                        missing_owners.insert(enc_by);
1204                    }
1205
1206                    if !db.pub_key_lookup.contains_key(&enc_for) {
1207                        missing_owners.insert(enc_for);
1208                    }
1209                }
1210            }
1211        }
1212
1213        let mut new_owners = HashMap::new();
1214        {
1215            for owner in missing_owners {
1216                let username_result = self
1217                    .client
1218                    .get_username(self.get_account().unwrap(), GetUsernameRequest { key: owner.0 })
1219                    .await;
1220                new_owners.insert(owner, username_result);
1221            }
1222        }
1223
1224        let mut tx = self.begin_tx().await;
1225        let db = tx.db();
1226
1227        let have_updates = !new_owners.is_empty();
1228        for (owner, username) in new_owners {
1229            let username = match username {
1230                Err(ApiError::Endpoint(GetUsernameError::UserNotFound)) => "<unknown>".to_string(),
1231                Ok(username) => username.username,
1232                _ => continue, // todo: possibly add some logging here
1233            };
1234
1235            db.pub_key_lookup.insert(owner, username).unwrap();
1236        }
1237
1238        if have_updates {
1239            self.events.meta_changed(Actor::Sync);
1240        }
1241
1242        Ok(())
1243    }
1244
1245    /// Updates remote and base metadata to local.
1246    async fn push_meta(&self) -> LbResult<()> {
1247        let mut updates = vec![];
1248        let mut local_changes_no_digests = Vec::new();
1249
1250        let tx = self.ro_tx().await;
1251        let db = tx.db();
1252
1253        // remote = local
1254        let local = db.base_metadata.stage(&db.local_metadata).to_lazy();
1255
1256        for id in local.tree.staged.ids() {
1257            let mut local_change = local.tree.staged.find(&id)?.timestamped_value.value.clone();
1258            let maybe_base_file = local.tree.base.maybe_find(&id);
1259
1260            // change everything but document hmac and re-sign
1261            local_change.set_hmac_and_size(
1262                maybe_base_file.and_then(|f| f.document_hmac().copied()),
1263                maybe_base_file.and_then(|f| *f.timestamped_value.value.doc_size()),
1264            );
1265            let local_change = local_change.sign(&self.keychain)?;
1266
1267            local_changes_no_digests.push(local_change.clone());
1268            let file_diff = FileDiff { old: maybe_base_file.cloned(), new: local_change };
1269            updates.push(file_diff);
1270        }
1271
1272        drop(tx);
1273
1274        if !updates.is_empty() {
1275            self.client
1276                .upsert_file_metadata_v2(
1277                    self.get_account()?,
1278                    UpsertRequestV2 { updates: updates.clone() },
1279                )
1280                .await?;
1281        }
1282
1283        let mut tx = self.begin_tx().await;
1284        let db = tx.db();
1285
1286        // base = local
1287        promote_pushed(&mut db.base_metadata, &mut db.local_metadata, local_changes_no_digests)?;
1288
1289        tx.end();
1290
1291        Ok(())
1292    }
1293
1294    /// Updates remote and base files to local. Assumes metadata is already pushed for all new files.
1295    // todo: make this so that all document updates are attempted and we don't just return the
1296    // first error. Once an attempt is made we can return any or all errors, either would be an
1297    // improvement
1298    async fn push_docs(&self) -> LbResult<()> {
1299        let mut updates = vec![];
1300        let mut local_changes_digests_only = vec![];
1301
1302        let tx = self.ro_tx().await;
1303        let db = tx.db();
1304        let start = Instant::now();
1305
1306        let local = db.base_metadata.stage(&db.local_metadata).to_lazy();
1307
1308        for id in local.tree.staged.ids() {
1309            let base_file = local.tree.base.find(&id)?.clone();
1310
1311            // change only document hmac and re-sign
1312            let mut local_change = base_file.timestamped_value.value.clone();
1313            local_change.set_hmac_and_size(
1314                local.find(&id)?.document_hmac().copied(),
1315                *local.find(&id)?.timestamped_value.value.doc_size(),
1316            );
1317
1318            if base_file.document_hmac() == local_change.document_hmac()
1319                || local_change.document_hmac().is_none()
1320            {
1321                continue;
1322            }
1323
1324            let local_change = local_change.sign(&self.keychain)?;
1325
1326            updates.push(FileDiff { old: Some(base_file), new: local_change.clone() });
1327            local_changes_digests_only.push(local_change);
1328            self.events
1329                .sync_update(SyncIncrement::PushingDocument(id, true));
1330        }
1331
1332        drop(tx);
1333        if start.elapsed() > web_time::Duration::from_millis(100) {
1334            warn!("sync push_docs held lock for {:?}", start.elapsed());
1335        }
1336
1337        let futures = updates.clone().into_iter().map(|diff| self.push_doc(diff));
1338
1339        let mut stream = stream::iter(futures).buffer_unordered(
1340            thread::available_parallelism()
1341                .unwrap_or(NonZeroUsize::new(4).unwrap())
1342                .into(),
1343        );
1344
1345        let mut docs_without_errors = vec![];
1346        let mut last_error: Option<LbErr> = None;
1347
1348        while let Some(fut) = stream.next().await {
1349            match fut {
1350                Ok(id) => {
1351                    docs_without_errors.push(id);
1352                    self.events
1353                        .sync_update(SyncIncrement::PushingDocument(id, false));
1354                }
1355                Err(err) => {
1356                    last_error = Some(err);
1357                }
1358            }
1359        }
1360
1361        local_changes_digests_only.retain(|f| docs_without_errors.contains(f.id()));
1362
1363        let mut tx = self.begin_tx().await;
1364        let db = tx.db();
1365        // base = local (metadata)
1366        promote_pushed(&mut db.base_metadata, &mut db.local_metadata, local_changes_digests_only)?;
1367
1368        tx.end();
1369
1370        if let Some(err) = last_error { Err(err) } else { Ok(()) }
1371    }
1372
1373    async fn push_doc(&self, diff: FileDiff<SignedMeta>) -> LbResult<Uuid> {
1374        let id = *diff.new.id();
1375        let hmac = diff.new.document_hmac();
1376        let hmac = *hmac.ok_or(LbErrKind::FileNonexistent)?;
1377        let local_document_change = self.docs.get(id, hmac).await?;
1378        self.client
1379            .change_doc_v2(
1380                self.get_account()?,
1381                ChangeDocRequestV2 { diff, new_content: local_document_change },
1382            )
1383            .await?;
1384
1385        Ok(id)
1386    }
1387
1388    #[cfg(not(target_family = "wasm"))]
1389    async fn send_debug_info(&self, account: Account) {
1390        use crate::service::debug;
1391
1392        let max_panic_time = debug::latest_panic_time(&self.config.writeable_path)
1393            .await
1394            .unwrap_or_else(|e| {
1395                warn!("could not enumerate panic files: {e:?}");
1396                None
1397            });
1398
1399        let last_sent = {
1400            let tx = self.ro_tx().await;
1401            tx.db().last_extracted_panic.as_ref().copied()
1402        };
1403
1404        let should_send = match (last_sent, max_panic_time) {
1405            (None, _) => true,
1406            (Some(prev), Some(cur)) => cur > prev,
1407            (Some(_), None) => false,
1408        };
1409
1410        if !should_send {
1411            return;
1412        }
1413
1414        let debug_info = match self.debug_info(false).await {
1415            Ok(debug_info) => debug_info,
1416            Err(e) => {
1417                warn!("could not collect debug_info: {e:?}");
1418                return;
1419            }
1420        };
1421
1422        let new_marker = max_panic_time.unwrap_or(0);
1423        let bg_self = self.clone();
1424        let task = async move {
1425            match bg_self
1426                .client
1427                .upsert_debug_info(&account, UpsertDebugInfoRequest { debug_info })
1428                .await
1429            {
1430                Ok(_) => {
1431                    let mut tx = bg_self.begin_tx().await;
1432                    if let Err(e) = tx.db().last_extracted_panic.replace(new_marker) {
1433                        warn!("could not record last_extracted_panic: {e:?}");
1434                    }
1435                    tx.end();
1436                }
1437                Err(e) => warn!("send_debug_info failed: {e:?}"),
1438            }
1439        };
1440
1441        if self.config.background_work {
1442            tokio::spawn(task);
1443        } else {
1444            task.await;
1445        }
1446    }
1447
1448    async fn read_document_helper<T>(
1449        &self, id: Uuid, tree: &mut LazyTree<T>,
1450    ) -> LbResult<DecryptedDocument>
1451    where
1452        T: TreeLike<F = SignedMeta>,
1453    {
1454        let file = tree.find(&id)?;
1455        validate::is_document(file)?;
1456        let hmac = file.document_hmac().copied();
1457
1458        let doc = match hmac {
1459            Some(hmac) => {
1460                let doc = self.docs.get(id, hmac).await?;
1461                tree.decrypt_document(&id, &doc, &self.keychain)?
1462            }
1463            None => vec![],
1464        };
1465
1466        Ok(doc)
1467    }
1468
1469    /// for tests only
1470    #[doc(hidden)]
1471    pub async fn server_dirty_ids(&self) -> LbResult<Vec<Uuid>> {
1472        let mut state = self.syncer.lock().await;
1473        #[cfg(not(any(target_family = "wasm", target_os = "ios")))]
1474        let _sync_lock = self.lock_sync()?;
1475        self.inital_sync_state(&mut state).await?;
1476        self.process_deletions().await?;
1477        self.fetch_meta(&mut state).await?;
1478
1479        let server_ids = state.remote_changes.iter().map(|f| *f.id()).collect();
1480
1481        Ok(server_ids)
1482    }
1483
1484    pub(crate) fn setup_syncer(&self) {
1485        if self.config.background_work {
1486            self.clone().local_change_worker();
1487            self.clone().periodic_sync_worker();
1488            self.clone().post_sync_worker();
1489        }
1490    }
1491
1492    fn local_change_worker(self) {
1493        #[cfg(not(target_family = "wasm"))]
1494        tokio::spawn(async move {
1495            let mut events = self.subscribe();
1496
1497            let sync_criteria = |e: Event| {
1498                matches!(
1499                    e,
1500                    Event::MetadataChanged(Actor::User(_))
1501                        | Event::DocumentWritten(_, Actor::User(_))
1502                )
1503            };
1504
1505            loop {
1506                time::sleep(Duration::from_millis(500)).await;
1507                let mut should_sync = false;
1508
1509                // drain the current channel, so we don't sync for each keystroke if they pile up
1510                loop {
1511                    match events.try_recv() {
1512                        Ok(event) => should_sync |= sync_criteria(event),
1513                        Err(TryRecvError::Empty) => break,
1514                        Err(TryRecvError::Lagged(_)) => should_sync |= self.has_local_work().await,
1515                        Err(TryRecvError::Closed) => return,
1516                    }
1517                }
1518
1519                // empty channel + nothing interesting has happened, sit and wait for something
1520                // interesting
1521                if !should_sync {
1522                    should_sync = match events.recv().await {
1523                        Ok(event) => sync_criteria(event),
1524                        Err(RecvError::Lagged(_)) => self.has_local_work().await,
1525                        Err(RecvError::Closed) => return,
1526                    };
1527                }
1528
1529                if should_sync {
1530                    self.sync().await.map_unexpected().log_and_ignore();
1531                }
1532            }
1533        });
1534    }
1535
1536    /// Whether a sync would push anything: what a missed event changed is still unsynced.
1537    #[cfg(not(target_family = "wasm"))]
1538    async fn has_local_work(&self) -> bool {
1539        !self.local_changes().await.is_empty()
1540    }
1541
1542    fn periodic_sync_worker(self) {
1543        #[cfg(not(target_family = "wasm"))]
1544        tokio::spawn(async move {
1545            loop {
1546                if self.user_active().await {
1547                    tokio::time::sleep(Duration::from_secs(3)).await;
1548                } else {
1549                    tokio::select! {
1550                        _ = tokio::time::sleep(Duration::from_secs(5 * 60)) => {}
1551                        _ = self.user_wake.notified() => {}
1552                    }
1553                }
1554                self.sync().await.map_unexpected().log_and_ignore();
1555            }
1556        });
1557    }
1558
1559    pub(crate) async fn user_active(&self) -> bool {
1560        let last_seen = self.user_last_seen.read().await;
1561        last_seen.elapsed() < Duration::from_secs(15)
1562    }
1563
1564    fn post_sync_worker(self) {
1565        #[cfg(not(target_family = "wasm"))]
1566        tokio::spawn(async move {
1567            let mut events = self.subscribe();
1568
1569            loop {
1570                // A receiver that lagged missed a sync's worth of events, a `SyncFinished`
1571                // possibly among them; the work after a sync is idempotent, so it runs again.
1572                match events.recv().await {
1573                    Ok(Event::Sync(SyncIncrement::SyncFinished(_))) | Err(RecvError::Lagged(_)) => {
1574                        self.fetcher().await.map_unexpected().log_and_ignore();
1575                        self.populate_pk_cache()
1576                            .await
1577                            .map_unexpected()
1578                            .log_and_ignore();
1579                    }
1580                    Ok(_) => {}
1581                    Err(RecvError::Closed) => return,
1582                }
1583            }
1584        });
1585    }
1586
1587    async fn fetcher(&self) -> LbResult<()> {
1588        let mut files_to_pull = vec![];
1589
1590        let tx = self.ro_tx().await;
1591        let db = tx.db();
1592
1593        let Some(root) = db.root.as_ref() else {
1594            return Ok(());
1595        };
1596
1597        // we can only fetch things we know the server knows about
1598        let mut tree = db.base_metadata.stage(None).to_lazy();
1599
1600        for id in tree.descendants_using_links(root)? {
1601            let file = tree.find(&id)?;
1602            let hmac = file.document_hmac().copied();
1603
1604            // skip non-documents
1605            if !file.is_document() {
1606                continue;
1607            }
1608
1609            // skip deleted files
1610            if tree.calculate_deleted(&id)? {
1611                continue;
1612            }
1613
1614            if hmac.is_some_and(|hmac| self.docs.exists(id, hmac)) {
1615                continue;
1616            }
1617
1618            // skip non-first-party files
1619            let name = tree.name(&id, &self.keychain)?;
1620            if !name.ends_with(".md") && !name.ends_with(".svg") {
1621                continue;
1622            }
1623
1624            files_to_pull.push((id, hmac));
1625        }
1626
1627        drop(tx);
1628
1629        // this could all be done in parallel, but for now going to not do it that way
1630        // benefits: less work, but also ensures that a file that needs to be fetched immediately
1631        // can be
1632        for (id, hmac) in files_to_pull {
1633            if let Some(hmac) = hmac {
1634                self.ensure_doc_available(id, hmac).await?;
1635            }
1636        }
1637
1638        Ok(())
1639    }
1640}
1641
1642/// Whether this device may still change `id` or what's in it: write is granted at the nearest file
1643/// `remote` has, at or above `id` in this device's tree, by a share this device hasn't declined,
1644/// and in this device's own tree. `remote` is the server's tree, with this device's kept moves
1645/// applied once they are, so shares are read where each file ends up, not the merge's.
1646fn may_write_in<L: TreeLike, R: TreeLike<F = L::F>>(
1647    local: &LazyTree<L>, remote: &LazyTree<R>, me: Owner, id: &Uuid,
1648) -> LbResult<bool> {
1649    if local.maybe_find(id).is_some()
1650        && local_access(local, remote, me, id)? < Some(UserAccessMode::Write)
1651    {
1652        return Ok(false);
1653    }
1654    let mut id = *id;
1655    while remote.maybe_find(&id).is_none() {
1656        let Some(file) = local.maybe_find(&id) else {
1657            return Ok(false);
1658        };
1659        if file.parent() == file.id() {
1660            return Ok(false);
1661        }
1662        id = *file.parent();
1663    }
1664    Ok(server_access(local, remote, me, &id)? >= Some(UserAccessMode::Write))
1665}
1666
1667/// This device's access to `id`: what its own tree grants, or more where the server's tree grants
1668/// more. The server's tree counts for `id` and each folder above it that the server places
1669/// differently, because that is where the file will end up:
1670/// - this device no longer has the folder's parent, as after losing a share;
1671/// - the server has the folder under another parent, as when this device moved it into a shared
1672///   folder that has since become read-only, and the move is about to be undone.
1673fn local_access<L: TreeLike, R: TreeLike<F = L::F>>(
1674    local: &LazyTree<L>, remote: &LazyTree<R>, me: Owner, id: &Uuid,
1675) -> LbResult<Option<UserAccessMode>> {
1676    let mut mode = local.access_mode(me, id)?;
1677    for id in local.access_sources(id)? {
1678        let file = local.find(&id)?;
1679        if file.is_root() {
1680            continue;
1681        }
1682        if let Some(placed) = remote.maybe_find(&id) {
1683            let elsewhere =
1684                local.maybe_find(file.parent()).is_none() || placed.parent() != file.parent();
1685            if elsewhere && remote.maybe_find(placed.parent()).is_some() {
1686                mode = mode.max(server_access(local, remote, me, placed.parent())?);
1687            }
1688        }
1689    }
1690    Ok(mode)
1691}
1692
1693/// The server's access at `id`, which `remote` has, less the shares this device declined.
1694fn server_access<L: TreeLike, R: TreeLike<F = L::F>>(
1695    local: &LazyTree<L>, remote: &LazyTree<R>, me: Owner, id: &Uuid,
1696) -> LbResult<Option<UserAccessMode>> {
1697    let mut mode = None;
1698    for id in remote.access_sources(id)? {
1699        let declined = local.maybe_find(&id).is_some_and(|file| {
1700            file.user_access_keys()
1701                .iter()
1702                .any(|key| key.encrypted_for == me.0 && key.deleted)
1703        });
1704        if !declined {
1705            mode = mode.max(remote.find(&id)?.access_mode(&me));
1706        }
1707    }
1708    Ok(mode)
1709}
1710
1711/// Promotes `pushed` into `base`, keeping local writes made during the push.
1712fn promote_pushed<B, L>(base: &mut B, local: &mut L, pushed: Vec<SignedMeta>) -> LbResult<()>
1713where
1714    B: TreeLikeMut<F = SignedMeta>,
1715    L: TreeLikeMut<F = SignedMeta>,
1716{
1717    // a local write can happen between push and promote
1718    let local_files = {
1719        let tree = base.stage(&*local);
1720        pushed
1721            .iter()
1722            .map(|f| tree.find(f.id()).cloned())
1723            .collect::<LbResult<Vec<_>>>()?
1724    };
1725    base.to_lazy().stage(pushed).promote()?;
1726    // this ensures those writes are not lost when the push is promoted
1727    for file in local_files {
1728        local.insert(file)?;
1729    }
1730    base.stage(local).prune()
1731}
1732
1733/// Undoes this device's moves that form a cycle, or fails when none of them is this device's.
1734/// An attachments folder in the cycle is there because of its document's place, so its
1735/// document's move is undone too; otherwise repair would move the folder back into the cycle.
1736fn unmove_cycle<L: TreeLike, T: TreeLike>(
1737    local: &L, local_changes: &T, ids: &HashSet<Uuid>, files_to_unmove: &mut HashSet<Uuid>,
1738) -> LbResult<()> {
1739    let mut progress = false;
1740    for &id in ids {
1741        let mut moved = vec![id];
1742        if let Some(of) = local.maybe_find(&id).and_then(|f| f.attachment_of()) {
1743            moved.push(of.id);
1744        }
1745        for id in moved {
1746            if local_changes.maybe_find(&id).is_some() && files_to_unmove.insert(id) {
1747                progress = true;
1748            }
1749        }
1750    }
1751    if !progress {
1752        return Err(LbErrKind::Unexpected(format!("sync failed to resolve cycle: {ids:?}")).into());
1753    }
1754    Ok(())
1755}
1756
1757/// `ids` ordered so each file comes after its ancestors that are also in `ids`.
1758fn parents_first<T: TreeLike>(tree: &LazyTree<T>, ids: &HashSet<Uuid>) -> LbResult<Vec<Uuid>> {
1759    let mut order = Vec::with_capacity(ids.len());
1760    let mut walked = HashSet::with_capacity(ids.len());
1761    for &id in ids {
1762        let mut unwalked_ancestry = Vec::new();
1763        let mut id = id;
1764        while walked.insert(id) {
1765            unwalked_ancestry.push(id);
1766            let Some(file) = tree.maybe_find(&id) else { break };
1767            id = *file.parent();
1768        }
1769        order.extend(
1770            unwalked_ancestry
1771                .into_iter()
1772                .rev()
1773                .filter(|id| ids.contains(id)),
1774        );
1775    }
1776    Ok(order)
1777}
1778
1779/// An attachments folder's document's parent, or a conflicting file's replacement parent, or a
1780/// normal file's normal parent
1781fn created_parent<T: TreeLike<F = SignedMeta>>(
1782    tree: &LazyTree<T>, file: &SignedMeta, replaced_folders: &HashMap<Uuid, Uuid>,
1783) -> Uuid {
1784    match tree.maybe_find_attached(file) {
1785        Some(document) => *document.parent(),
1786        None => replacement(replaced_folders, file.parent()),
1787    }
1788}
1789
1790/// `folder`, or the folder that replaces it.
1791fn replacement(replaced_folders: &HashMap<Uuid, Uuid>, folder: &Uuid) -> Uuid {
1792    *replaced_folders.get(folder).unwrap_or(folder)
1793}
1794
1795/// A creation whose parent is in neither the tree nor the creations before it.
1796fn orphaned_creation(id: Uuid) -> impl FnOnce(LbErr) -> LbErr {
1797    move |err| match err.kind {
1798        LbErrKind::FileParentNonexistent => LbErrKind::Unexpected(format!(
1799            "sync failed to find a topological order for file creation {id}"
1800        ))
1801        .into(),
1802        _ => err,
1803    }
1804}
1805
1806/// A file this device has no access to, e.g. inside a share it declined. A share root carrying
1807/// this device's own (possibly tombstoned) key is not lost: that tombstone is what gets pushed.
1808fn lost_access<L: TreeLike, R: TreeLike<F = L::F>>(
1809    local: &LazyTree<L>, remote: &LazyTree<R>, me: Owner, id: &Uuid,
1810) -> LbResult<bool> {
1811    let is_my_share_root = local
1812        .find(id)?
1813        .user_access_keys()
1814        .iter()
1815        .any(|k| k.encrypted_for == me.0);
1816    let reachable = local_access(local, remote, me, id)?.is_some();
1817    Ok(!is_my_share_root && !reachable)
1818}
1819
1820/// Each recipient's share of a file as (mode, deleted); a file keeps one share per recipient.
1821fn shares_by_recipient(file: Option<&SignedMeta>) -> HashMap<Owner, (UserAccessMode, bool)> {
1822    file.into_iter()
1823        .flat_map(|file| file.user_access_keys())
1824        .map(|key| (Owner(key.encrypted_for), (key.mode, key.deleted)))
1825        .collect()
1826}