lb-rs 26.11.26

The rust library for interacting with your lockbook.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
use crate::io::docs::LocalDocuments;
use crate::io::server::Server;
use std::{
    collections::{HashMap, HashSet},
    num::NonZeroUsize,
    sync::Arc,
    thread,
    time::{Duration, Instant},
};

#[cfg(not(any(target_family = "wasm", target_os = "ios")))]
use std::fs::{File, TryLockError};

use futures::{StreamExt, stream};
use tokio::sync::Mutex;
#[cfg(not(target_family = "wasm"))]
use tokio::sync::broadcast::error::{RecvError, TryRecvError};
use tokio::time;
use uuid::Uuid;

use crate::{
    Lb, LbErrKind, LbResult,
    io::network::ApiError,
    model::{
        ValidationFailure,
        access_info::UserAccessMode,
        account::Account,
        api::{
            ChangeDocRequestV2, GetDocRequest, GetFileIdsRequest, GetUpdatesRequestV2,
            GetUsernameError, GetUsernameRequest, UpsertDebugInfoRequest, UpsertRequestV2,
        },
        crypto::{AESKey, DecryptedDocument, EncryptedDocument},
        errors::{LbErr, Unexpected},
        file::ShareMode,
        file_like::FileLike,
        file_metadata::{DocumentHmac, FileDiff, FileType, Owner},
        filename::{DocumentType, NameComponents},
        lazy::LazyTree,
        signed_meta::SignedMeta,
        staged::StagedTreeLikeMut,
        symkey,
        tree_like::{TreeLike, TreeLikeMut},
        validate,
    },
    service::events::{Actor, Event, SyncIncrement},
};

pub type Syncer = Arc<Mutex<SyncState>>;

#[derive(Default)]
pub struct SyncState {
    /// the starting point for updates for this sync pass
    last_synced: u64,

    /// if our pull is successful, this is the timestamp we will commit
    updates_as_of: u64,

    /// changes we pulled from the server, post deduplication
    remote_changes: Vec<SignedMeta>,

    /// did we pull a root on this pass?
    new_root: Option<Uuid>,

    /// what docs did we pull as a result of this sync
    pulled_docs: Vec<Uuid>,
}

// we are gonna have a fetch metadata fn which will get the docs that it needs to get, the ones
// that match should_fetch
//
// should_fetch is going to be a tree fn that will return true if:
//     is md or svg that descends from

impl<S: Server, D: LocalDocuments> Lb<S, D> {
    /// Outside iOS and WASM, returns `AlreadySyncing` if another instance is syncing this data directory.
    #[instrument(level = "debug", skip(self), err(Debug))]
    pub async fn sync(&self) -> LbResult<()> {
        let mut sync_state = self.syncer.lock().await;
        #[cfg(not(any(target_family = "wasm", target_os = "ios")))]
        let _sync_lock = self.lock_sync()?;
        self.events.sync_update(SyncIncrement::SyncStarted);

        let pipeline: LbResult<()> = async {
            self.pull_updates(&mut sync_state).await?;
            self.push_local_changes().await?;
            Ok(())
        }
        .await;

        self.events.sync_update(SyncIncrement::SyncFinished(
            pipeline.as_ref().err().map(|err| err.kind.clone()),
        ));

        self.cleanup().await?;

        pipeline?;

        let account = self.get_account()?.clone();

        #[cfg(not(target_family = "wasm"))]
        if account.is_beta() {
            self.send_debug_info(account).await;
        }

        Ok(())
    }

    #[cfg(not(any(target_family = "wasm", target_os = "ios")))]
    fn lock_sync(&self) -> LbResult<Option<File>> {
        let Some(path) = &self.sync_lock else {
            return Ok(None);
        };
        let file = File::options()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false)
            .open(path)?;
        match file.try_lock() {
            Ok(()) => Ok(Some(file)),
            Err(TryLockError::WouldBlock) => Err(LbErrKind::AlreadySyncing.into()),
            Err(TryLockError::Error(err)) => Err(err.into()),
        }
    }

    pub(crate) async fn pull_updates(&self, sync_state: &mut SyncState) -> LbResult<()> {
        self.inital_sync_state(sync_state).await?;
        self.process_deletions().await?;
        self.fetch_meta(sync_state).await?;
        self.fetch_required_docs(sync_state).await?;
        // todo: should this inform a re-pull?
        self.merge(sync_state).await?;
        self.commit_last_synced(sync_state).await?;
        self.send_pull_events(sync_state).await?;

        if !self.config.background_work {
            self.populate_pk_cache().await?;
        }

        Ok(())
    }

    pub(crate) async fn push_local_changes(&self) -> LbResult<()> {
        self.create_shared_attachments().await?;
        self.push_meta().await?;
        self.push_docs().await?;

        Ok(())
    }

    /// For each note of mine that someone else can write, if it has no attachments folder, make one
    async fn create_shared_attachments(&self) -> LbResult<()> {
        if !self.attachments_folders {
            return Ok(());
        }
        let me = Owner(self.keychain.get_pk()?);
        let mut tx = self.begin_tx().await;
        let db = tx.db();
        let mut tree = (&db.base_metadata)
            .to_staged(&mut db.local_metadata)
            .to_lazy();
        let mut ids = tree.ids();
        ids.sort();
        let mut created = false;
        for id in ids {
            if tree.wants_attachments(&id, me)? {
                tree.create_attachments(
                    self.entropy.id(),
                    self.entropy.key(),
                    &id,
                    &self.keychain,
                )?;
                created = true;
            }
        }
        tx.end();
        if created {
            self.events.meta_changed(Actor::Sync);
        }
        Ok(())
    }

    async fn inital_sync_state(&self, state: &mut SyncState) -> LbResult<()> {
        // Catch up after acquiring the sync lock, before using the previous sync's cursor.
        let mut tx = self.begin_tx().await;
        let db = tx.db();

        *state = Default::default();
        state.last_synced = db.last_synced.as_ref().copied().unwrap_or_default() as u64;
        tx.end();

        Ok(())
    }

    pub(crate) async fn process_deletions(&self) -> LbResult<()> {
        let server_ids = self
            .client
            .get_file_ids(self.get_account()?, GetFileIdsRequest {})
            .await?
            .ids;

        let mut tx = self.begin_tx().await;
        let db = tx.db();

        let mut local = db.base_metadata.stage(&db.local_metadata).to_lazy();
        let base_ids = local.tree.base.ids();

        // files the server stopped listing and unlisted files whose existence is tied to them:
        // their children and attachments
        let mut prunable_ids: HashSet<Uuid> = base_ids
            .into_iter()
            .filter(|id| !server_ids.contains(id))
            .collect();
        let mut attached: HashMap<Uuid, Vec<Uuid>> = HashMap::new();
        for id in local.ids() {
            if let Some(of) = local.find(&id)?.attachment_of() {
                attached.entry(of.id).or_default().push(id);
            }
        }
        let mut to_visit: Vec<Uuid> = prunable_ids.iter().copied().collect();
        while let Some(id) = to_visit.pop() {
            let mut under = Vec::new();
            for child in local.children(&id)? {
                // concurrent edits can leave an attachments folder looking like it should be pruned
                // without an exception for when its document is not
                let follows_document = local
                    .find(&child)?
                    .attachment_of()
                    .is_some_and(|of| server_ids.contains(&of.id));
                if !follows_document {
                    under.push(child);
                }
            }
            under.extend(attached.get(&id).into_iter().flatten().copied());
            for child in under {
                if !server_ids.contains(&child) && prunable_ids.insert(child) {
                    to_visit.push(child);
                }
            }
        }

        // a file the server still has keeps its other changes: a pending move into a pruned
        // folder is undone
        let mut moved_in = Vec::new();
        for id in db.local_metadata.ids() {
            let parent = *local.find(&id)?.parent();
            if let Some(base_file) = local.tree.base.maybe_find(&id) {
                if prunable_ids.contains(&parent)
                    && !prunable_ids.contains(&id)
                    && !prunable_ids.contains(base_file.parent())
                {
                    moved_in.push((id, *base_file.parent()));
                }
            }
        }
        for id in &prunable_ids {
            if let Some(&hmac) = local
                .tree
                .base
                .maybe_find(id)
                .and_then(|f| f.document_hmac())
            {
                self.docs.delete(*id, hmac).await?;
            }
            if let Some(&hmac) = local.maybe_find(id).and_then(|f| f.document_hmac()) {
                self.docs.delete(*id, hmac).await?;
            }
        }

        let mut tree = (&db.base_metadata)
            .to_staged(&mut db.local_metadata)
            .to_lazy();
        for (id, parent) in moved_in {
            tree.move_unvalidated(&id, &parent, &self.keychain)?;
        }

        let mut base_staged = (&mut db.base_metadata).to_lazy().stage(None);
        base_staged.tree.removed = prunable_ids.iter().copied().collect();
        base_staged.promote()?;

        let mut local_staged = (&mut db.local_metadata).to_lazy().stage(None);
        local_staged.tree.removed = prunable_ids.iter().copied().collect();
        local_staged.promote()?;

        if !prunable_ids.is_empty() {
            self.events.meta_changed(Actor::Sync);
        }

        Ok(())
    }

    async fn fetch_meta(&self, state: &mut SyncState) -> LbResult<()> {
        let updates = self
            .client
            .get_updates_v2(
                self.get_account()?,
                GetUpdatesRequestV2 { since_metadata_version: state.last_synced },
            )
            .await?;

        let tx = self.ro_tx().await;
        let db = tx.db();

        // this loop implicitly prunes remote orphans; like validation, a deleted file whose
        // parent left the tree is not one
        let mut without_orphans = Vec::new();
        let me = Owner(self.keychain.get_pk()?);
        let remote = db.base_metadata.stage(updates.file_metadata).to_lazy();
        for id in remote.tree.staged.ids() {
            let meta = remote.find(&id)?;
            if remote.maybe_find_parent(meta).is_some()
                || remote.maybe_find_attached(meta).is_some()
                || meta.explicitly_deleted()
                || meta
                    .user_access_keys()
                    .iter()
                    .any(|k| k.encrypted_for == me.0)
            {
                without_orphans.push(remote.find(&id)?.clone());
            }
        }

        // this is what actually performs the deduplication
        let pruned_tree = db.base_metadata.stage(without_orphans).pruned()?.to_lazy();
        let (_, deduped_changes) = pruned_tree.unstage();

        // initialize root if this is the first pull on this device
        let mut root_id = None;
        if db.root.as_ref().is_none() {
            let root = deduped_changes
                .all_files()?
                .into_iter()
                .find(|f| f.is_root())
                .ok_or(LbErrKind::RootNonexistent)?;
            root_id = Some(*root.id());
        }

        state.remote_changes = deduped_changes;
        state.updates_as_of = updates.as_of_metadata_version;
        state.new_root = root_id;

        Ok(())
    }

    async fn fetch_required_docs(&self, state: &mut SyncState) -> LbResult<()> {
        let mut docs_to_pull = vec![];

        let tx = self.ro_tx().await;
        let db = tx.db();

        let mut files_with_local_edits = vec![];
        let local = db.base_metadata.stage(&db.local_metadata);
        for id in local.staged.ids() {
            if let Some(base) = local.base.maybe_find(&id) {
                if let Some(local_hmac) = local.find(&id)?.document_hmac() {
                    if Some(local_hmac) != base.document_hmac() {
                        files_with_local_edits.push(id);
                    }
                }
            }
        }

        let mut remote = db
            .base_metadata
            .stage(state.remote_changes.clone())
            .to_lazy();

        for id in remote.tree.staged.ids() {
            if remote.calculate_deleted(&id)? {
                continue;
            }
            let remote_hmac = remote.find(&id)?.document_hmac().cloned();
            let base_hmac = remote
                .tree
                .base
                .maybe_find(&id)
                .and_then(|f| f.document_hmac())
                .cloned();
            if base_hmac == remote_hmac {
                continue;
            }

            if let Some(remote_hmac) = remote_hmac {
                // pull a file if we have a prior base, this is our heuristic -- do they have the
                // ability to edit this file while we release the lock and are pulling all the
                // files
                if base_hmac.is_some_and(|base_hmac| self.docs.exists(id, base_hmac))
                    && !self.docs.exists(id, remote_hmac)
                {
                    docs_to_pull.push((id, remote_hmac));
                }

                // this clause captures documents which went from being new -> multiple parties
                // having updates. We'll still need the updates
                if files_with_local_edits.contains(&id)
                    && !docs_to_pull
                        .iter()
                        .any(|(already_pulling, _)| already_pulling == &id)
                {
                    if let Some(base_hmac) = base_hmac {
                        if !self.docs.exists(id, base_hmac) {
                            // this scenario basically only comes up in tests
                            // someone modifies a file directly without reading the prior version
                            docs_to_pull.push((id, base_hmac));
                        }
                    }
                    docs_to_pull.push((id, remote_hmac));
                }
            }
        }
        drop(tx);

        let futures = docs_to_pull
            .into_iter()
            .map(|(id, hmac)| async move { self.ensure_doc_available(id, hmac).await.map(|_| id) });

        let mut stream = stream::iter(futures).buffer_unordered(
            thread::available_parallelism()
                .unwrap_or(NonZeroUsize::new(4).unwrap())
                .into(),
        );

        while let Some(fut) = stream.next().await {
            let id = fut?;
            state.pulled_docs.push(id);
        }

        Ok(())
    }

    pub(crate) async fn ensure_doc_available(
        &self, id: Uuid, hmac: DocumentHmac,
    ) -> LbResult<Option<EncryptedDocument>> {
        // todo: in a lot of cases there is a list of ids we're trying to get, it would be better
        // if the caller managed the event updates, the status would be more meaningful for longer

        // in this world, can we get stuck pushing a doc as well? Probably fine for now
        if self.docs.exists(id, hmac) {
            return Ok(None);
        }

        self.events
            .sync_update(SyncIncrement::PullingDocument(id, true));
        let remote_document = self
            .client
            .get_document(self.get_account()?, GetDocRequest { id, hmac })
            .await?;
        self.docs.insert(id, hmac, &remote_document.content).await?;
        self.events
            .sync_update(SyncIncrement::PullingDocument(id, false));

        Ok(Some(remote_document.content))
    }

    pub(crate) async fn fetch_doc(
        &self, id: Uuid, hmac: DocumentHmac,
    ) -> LbResult<EncryptedDocument> {
        match self.ensure_doc_available(id, hmac).await? {
            Some(doc) => Ok(doc),
            None => self.docs.get(id, hmac).await,
        }
    }

    /// Pulls remote changes and constructs a changeset Merge such that Stage<Stage<Stage<Base, Remote>, Local>, Merge> is valid.
    /// Promotes Base to Stage<Base, Remote> and Local to Stage<Local, Merge>
    async fn merge(&self, state: &mut SyncState) -> LbResult<()> {
        let mut tx = self.begin_tx().await;
        let db = tx.db();
        let start = Instant::now();

        let remote_changes = &state.remote_changes;

        // fetch document updates and local documents for merge
        let me = Owner(self.keychain.get_pk()?);

        // compute merge changes
        let merge_changes = {
            // assemble trees
            let mut base = (&db.base_metadata).to_lazy();
            let remote_unlazy = (&db.base_metadata).to_staged(remote_changes);
            let mut remote = remote_unlazy.as_lazy();
            let mut local = (&db.base_metadata).to_staged(&db.local_metadata).to_lazy();

            // changeset constraints - these evolve as we try to assemble changes and encounter validation failures
            let mut files_to_unmove: HashSet<Uuid> = HashSet::new();
            let mut files_to_unshare: HashSet<Uuid> = HashSet::new();
            let mut links_to_delete: HashSet<Uuid> = HashSet::new();
            // folders this device created that sync replaces with one the server already has; the
            // contents go in the replacement
            let mut replaced_folders: HashMap<Uuid, Uuid> = HashMap::new();
            let mut rename_increments: HashMap<Uuid, usize> = HashMap::new();
            // Id and key share one lifetime: the merge, including construction retries.
            // A new key per attempt encrypts with the key cached by the failed attempt.
            let mut duplicate_file_ids: HashMap<Uuid, (Uuid, AESKey)> = HashMap::new();

            'merge_construction: loop {
                // judged afresh each attempt, since an undone cycle can change a destination's access
                let mut refused_moves: HashSet<Uuid> = HashSet::new();
                // process just the edits which allow us to check deletions in the result
                let mut remote_with_moves = {
                    let mut remote_with_moves = remote_unlazy.stage(Vec::new()).to_lazy();

                    // creations
                    let mut deletion_creations = HashSet::new();
                    for id in db.local_metadata.ids() {
                        if remote.maybe_find(&id).is_none()
                            && !links_to_delete.contains(&id)
                            && !replaced_folders.contains_key(&id)
                        {
                            deletion_creations.insert(id);
                        }
                    }
                    for id in parents_first(&local, &deletion_creations)? {
                        let local_file = local.find(&id)?.clone();
                        let parent =
                            created_parent(&remote_with_moves, &local_file, &replaced_folders);
                        remote_with_moves
                            .create_unvalidated(
                                id,
                                symkey::generate_key(),
                                &parent,
                                &local.name(&id, &self.keychain)?,
                                local_file.file_type(),
                                local_file.attachment_of().cloned(),
                                &self.keychain,
                            )
                            .map_err(orphaned_creation(id))?;
                    }

                    // moves (creations happen first in case a file is moved into a new folder);
                    // as in the merge, skipping files the server moved or deleted; parents first,
                    // so a destination is judged where its own kept move puts it
                    let local_ids = db.local_metadata.ids().into_iter().collect();
                    for id in parents_first(&local, &local_ids)? {
                        let local_file = local.find(&id)?.clone();
                        if let Some(base_file) = db.base_metadata.maybe_find(&id).cloned() {
                            if !local_file.explicitly_deleted()
                                && local_file.parent() != base_file.parent()
                                && remote.find(&id)?.parent() == base_file.parent()
                                && !remote.calculate_deleted(&id)?
                                && !files_to_unmove.contains(&id)
                            {
                                // a move this device may no longer make is undone; at the source
                                // only the server's grant counts, since leaving a share after
                                // moving out of it is this device's own later change
                                let from = remote.find(&id)?.parent();
                                let may_move_from = remote.maybe_find(from).is_some()
                                    && remote.access_mode(me, from)? >= Some(UserAccessMode::Write);
                                let to = replacement(&replaced_folders, local_file.parent());
                                if !may_move_from
                                    || !may_write_in(&local, &remote_with_moves, me, &to)?
                                {
                                    refused_moves.insert(id);
                                    continue;
                                }
                                // move
                                remote_with_moves.move_unvalidated(&id, &to, &self.keychain)?;
                            }
                        }
                    }

                    // deletions (moves happen first in case a file is moved into a deleted folder)
                    for id in db.local_metadata.ids() {
                        let local_file = local.find(&id)?.clone();
                        let parent = *remote.maybe_find(&id).unwrap_or(&local_file).parent();
                        if local_file.explicitly_deleted()
                            && !lost_access(&local, &remote, me, &id)?
                            && may_write_in(&local, &remote, me, &parent)?
                        {
                            // delete
                            remote_with_moves.delete_unvalidated(&id, &self.keychain)?;
                        }
                    }
                    remote_with_moves
                };

                // process all edits, dropping non-deletion edits for files that will be implicitly deleted
                let mut merge = {
                    let mut merge = remote_unlazy.stage(Vec::new()).to_lazy();

                    // creations and edits of created documents
                    let mut creations = HashSet::new();
                    for id in db.local_metadata.ids() {
                        if remote_with_moves.maybe_find(&id).is_some()
                            && !remote_with_moves.calculate_deleted(&id)?
                            && remote.maybe_find(&id).is_none()
                            && !links_to_delete.contains(&id)
                            && !lost_access(&local, &remote, me, &id)?
                            && may_write_in(
                                &local,
                                &remote_with_moves,
                                me,
                                &created_parent(
                                    &remote_with_moves,
                                    local.find(&id)?,
                                    &replaced_folders,
                                ),
                            )?
                        {
                            creations.insert(id);
                        }
                    }
                    for id in parents_first(&local, &creations)? {
                        let local_file = local.find(&id)?.clone();
                        let parent = created_parent(&merge, &local_file, &replaced_folders);
                        merge
                            .create_unvalidated(
                                id,
                                local.decrypt_key(&id, &self.keychain)?,
                                &parent,
                                &local.name(&id, &self.keychain)?,
                                local_file.file_type(),
                                local_file.attachment_of().cloned(),
                                &self.keychain,
                            )
                            .map_err(orphaned_creation(id))?;
                    }

                    // deletes
                    // before moves, so a moved folder leaves the files this device deleted as they
                    // were; a file is deleted itself unless its parent is deleted and holds it in
                    // the merge too, since moves skip deleted files but may lift live ones
                    for id in db.local_metadata.ids() {
                        if db.base_metadata.maybe_find(&id).is_none()
                            || !remote_with_moves.calculate_deleted(&id)?
                            || remote.calculate_deleted(&id)?
                        {
                            continue;
                        }
                        let deleted = remote_with_moves.find(&id)?;
                        if deleted.explicitly_deleted()
                            || deleted.parent() != merge.find(&id)?.parent()
                        {
                            // delete
                            merge.delete_unvalidated(&id, &self.keychain)?;
                        }
                    }
                    for &id in &links_to_delete {
                        // delete
                        if merge.maybe_find(&id).is_some()
                            && !merge.find(&id)?.explicitly_deleted()
                            && !(remote.maybe_find(&id).is_some()
                                && remote.calculate_deleted(&id)?)
                        {
                            merge.delete_unvalidated(&id, &self.keychain)?;
                        }
                    }

                    // skip files that are already deleted, will be deleted, were not created, or
                    // are no longer reachable from this device
                    let mut replayed = Vec::new();
                    for id in db.local_metadata.ids() {
                        if merge.maybe_find(&id).is_some()
                            && remote_with_moves.maybe_find(&id).is_some()
                            && !remote_with_moves.calculate_deleted(&id)?
                            && !(remote.maybe_find(&id).is_some()
                                && remote.calculate_deleted(&id)?)
                            && !links_to_delete.contains(&id)
                            && !lost_access(&local, &remote, me, &id)?
                        {
                            replayed.push(id);
                        }
                    }

                    // moves (creations happen first in case a file is moved into a new folder)
                    for &id in &replayed {
                        let local_file = local.find(&id)?;
                        if let Some(base_file) = base.maybe_find(&id) {
                            if local_file.parent() != base_file.parent()
                                && remote.find(&id)?.parent() == base_file.parent()
                                && !files_to_unmove.contains(&id)
                                && !refused_moves.contains(&id)
                            {
                                let parent = replacement(&replaced_folders, local_file.parent());
                                merge.move_unvalidated(&id, &parent, &self.keychain)?;
                            }
                        }
                    }
                    // access is read from the merge below, which needs a tree without cycles; the
                    // full validation after construction reports every other failure
                    if let Err(LbErr {
                        kind: LbErrKind::Validation(ValidationFailure::Cycle(ids)),
                        ..
                    }) = merge.assert_no_cycles()
                    {
                        unmove_cycle(&local, &db.local_metadata, &ids, &mut files_to_unmove)?;
                        continue 'merge_construction;
                    }

                    // renames, edits, and shares (moves happen first so each file is where
                    // the merge puts it)
                    for id in replayed {
                        let local_file = local.find(&id)?.clone();
                        let local_name = local.name(&id, &self.keychain)?;
                        let maybe_base_file = base.maybe_find(&id).cloned();
                        let maybe_remote_file = remote.maybe_find(&id).cloned();
                        if maybe_base_file.is_some() {
                            let base_name = base.name(&id, &self.keychain)?;
                            let remote_name = remote.name(&id, &self.keychain)?;

                            // rename
                            if local_name != base_name
                                && remote_name == base_name
                                && may_write_in(
                                    &local,
                                    &remote_with_moves,
                                    me,
                                    merge.find(&id)?.parent(),
                                )?
                            {
                                merge.rename_unvalidated(&id, &local_name, &self.keychain)?;
                            }
                        }

                        // share: replay what this device changed about each recipient's share;
                        // when the server changed it too, this device wins if either side unshared,
                        // otherwise the higher mode
                        let writable = may_write_in(&local, &remote_with_moves, me, &id)?;
                        let base_keys = shares_by_recipient(maybe_base_file.as_ref());
                        let remote_keys = shares_by_recipient(maybe_remote_file.as_ref());
                        let owner = merge.find(&id)?.owner();
                        // in the file's order, so shares keep the order they were added in; a
                        // recipient's last key is its share, as in shares_by_recipient
                        let keys = local_file.user_access_keys();
                        for (i, key) in keys.iter().enumerate() {
                            if keys[i + 1..]
                                .iter()
                                .any(|k| k.encrypted_for == key.encrypted_for)
                            {
                                continue;
                            }
                            let (for_, local) = (Owner(key.encrypted_for), (key.mode, key.deleted));
                            let base = base_keys.get(&for_).copied();
                            // a move may have made the recipient the owner, whose share only an
                            // unshare changes
                            if Some(local) == base || (for_ == owner && !local.1) {
                                continue;
                            }
                            let remote = remote_keys.get(&for_).copied();
                            let remote_live = remote.filter(|&(_, deleted)| !deleted);
                            let (mode, deleted) = local;
                            if deleted {
                                let mine = for_ == me;
                                if remote_live.is_some() && (mine || writable) {
                                    merge.delete_share_unvalidated(
                                        &id,
                                        Some(for_.0),
                                        &self.keychain,
                                    )?;
                                }
                                continue;
                            }
                            let wins = remote == base
                                || remote_live.is_none_or(|(remote_mode, _)| mode > remote_mode);
                            let mode = match mode {
                                UserAccessMode::Read => ShareMode::Read,
                                UserAccessMode::Write => ShareMode::Write,
                                UserAccessMode::Owner => continue,
                            };
                            if wins && writable {
                                merge.add_share_unvalidated(id, for_, mode, &self.keychain)?;
                            }
                        }
                        // share deletion due to conflicts
                        if files_to_unshare.contains(&id) {
                            merge.delete_share_unvalidated(&id, None, &self.keychain)?;
                        }

                        // rename due to path conflict
                        if let Some(&rename_increment) = rename_increments.get(&id) {
                            let name = if local_file.is_folder() {
                                NameComponents::folder(&local_name)
                            } else {
                                NameComponents::from(&local_name)
                            };
                            let name = name.numbered(rename_increment + 1);
                            merge.rename_unvalidated(&id, &name, &self.keychain)?;
                        }

                        // edit
                        let base_hmac = maybe_base_file.and_then(|f| f.document_hmac().cloned());
                        let remote_hmac =
                            maybe_remote_file.and_then(|f| f.document_hmac().cloned());
                        let local_hmac = local_file.document_hmac().cloned();
                        if may_write_in(&local, &remote_with_moves, me, &id)?
                            && local_hmac != base_hmac
                        {
                            if remote_hmac != base_hmac && remote_hmac != local_hmac {
                                // merge
                                let merge_name = merge.name(&id, &self.keychain)?;
                                let document_type =
                                    DocumentType::from_file_name_using_extension(&merge_name);

                                // todo these accesses are potentially problematic
                                // maybe not if service/docs is the persion doing network io
                                let base_document =
                                    self.read_document_helper(id, &mut base).await?;
                                let remote_document =
                                    self.read_document_helper(id, &mut remote).await?;
                                let local_document =
                                    self.read_document_helper(id, &mut local).await?;

                                match document_type.merge(
                                    &base_document,
                                    &local_document,
                                    &remote_document,
                                ) {
                                    Some(merged_document) => {
                                        let encrypted_document = merge
                                            .update_document_unvalidated(
                                                &id,
                                                &merged_document,
                                                &self.keychain,
                                            )?;
                                        if let Some(&hmac) = merge.find(&id)?.document_hmac() {
                                            self.docs.insert(id, hmac, &encrypted_document).await?;
                                        }
                                    }
                                    None => {
                                        // duplicate file, in the document's folder if this device
                                        // may write there, otherwise beside its link; with no
                                        // link there's nowhere to put it
                                        let parent = *merge.find(&id)?.parent();
                                        let writable = merge.maybe_find(&parent).is_some()
                                            && may_write_in(
                                                &local,
                                                &remote_with_moves,
                                                me,
                                                &parent,
                                            )?;
                                        let copy_parent = if writable {
                                            Some(parent)
                                        } else if let Some(link) = merge.linked_by(&id)? {
                                            Some(*merge.find(&link)?.parent())
                                        } else {
                                            None
                                        };
                                        if let Some(merge_parent) = copy_parent {
                                            let (duplicate_id, duplicate_key) =
                                                if let Some(&tracked) = duplicate_file_ids.get(&id)
                                                {
                                                    tracked
                                                } else {
                                                    let duplicate_id = self.entropy.id();
                                                    let duplicate_key = self.entropy.key();
                                                    duplicate_file_ids
                                                        .insert(id, (duplicate_id, duplicate_key));
                                                    rename_increments.insert(duplicate_id, 1);
                                                    (duplicate_id, duplicate_key)
                                                };

                                            let merge_name = NameComponents::from(&merge_name)
                                                .copy(rename_increments[&duplicate_id]);

                                            merge.create_unvalidated(
                                                duplicate_id,
                                                duplicate_key,
                                                &merge_parent,
                                                &merge_name,
                                                FileType::Document,
                                                None,
                                                &self.keychain,
                                            )?;
                                            let encrypted_document = merge
                                                .update_document_unvalidated(
                                                    &duplicate_id,
                                                    &local_document,
                                                    &self.keychain,
                                                )?;
                                            if let Some(&duplicate_hmac) =
                                                merge.find(&duplicate_id)?.document_hmac()
                                            {
                                                self.docs
                                                    .insert(
                                                        duplicate_id,
                                                        duplicate_hmac,
                                                        &encrypted_document,
                                                    )
                                                    .await?;
                                            }
                                        }
                                    }
                                }
                            } else {
                                let local_file = local.find(&id)?;
                                merge.overwrite_document_hmac_unvalidated(
                                    &id,
                                    local_file.document_hmac().copied(),
                                    local_file.doc_size(),
                                    &self.keychain,
                                )?;
                            }
                        }
                    }

                    // repair: each attachments folder goes beside its document, keeping its name;
                    // documents in id order so every device repairs a tree the same way
                    let mut attached = Vec::new();
                    for id in merge.ids() {
                        if let Some(of) = merge.find(&id)?.attachment_of() {
                            attached.push((of.id, id));
                        }
                    }
                    attached.sort();
                    for (document, folder) in attached {
                        if merge.maybe_find(&document).is_none()
                            || merge.calculate_deleted(&document)?
                            || merge.calculate_deleted(&folder)?
                        {
                            continue;
                        }
                        let parent = *merge.find(&document)?.parent();
                        let folder_parent = *merge.find(&folder)?.parent();
                        if parent != folder_parent
                            && may_write_in(&local, &remote_with_moves, me, &parent)?
                            && may_write_in(&local, &remote_with_moves, me, &folder_parent)?
                        {
                            merge.move_attachments_beside_note(
                                &document,
                                &folder,
                                &self.keychain,
                            )?;
                        }
                    }

                    merge
                };

                // validate; handle failures by introducing changeset constraints
                for link in merge.ids() {
                    if !merge.calculate_deleted(&link)? {
                        if let FileType::Link { target } = merge.find(&link)?.file_type() {
                            if merge.maybe_find(&target).is_some()
                                && merge.calculate_deleted(&target)?
                            {
                                // delete links to deleted files
                                if links_to_delete.insert(link) {
                                    continue 'merge_construction;
                                } else {
                                    return Err(LbErrKind::Unexpected(format!(
                                        "sync failed to resolve broken link (deletion): {link:?}"
                                    ))
                                    .into());
                                }
                            }
                        }
                    }
                }

                let validate_result = merge.validate(me);
                match validate_result {
                    // merge changeset is valid
                    Ok(_) => {
                        let (_, merge_changes) = merge.unstage();
                        break merge_changes;
                    }
                    Err(ref err) => match err.kind {
                        LbErrKind::Validation(ref vf) => match vf {
                            // merge changeset has resolvable validation errors and needs modification
                            ValidationFailure::Cycle(ids) => {
                                unmove_cycle(
                                    &local,
                                    &db.local_metadata,
                                    ids,
                                    &mut files_to_unmove,
                                )?;
                            }
                            ValidationFailure::PathConflict(ids) => {
                                // pick one local id and generate a non-conflicting filename
                                let mut progress = false;
                                for &id in ids {
                                    if duplicate_file_ids.values().any(|&(dup, _)| dup == id) {
                                        *rename_increments.entry(id).or_insert(0) += 1;
                                        progress = true;
                                        break;
                                    }
                                }
                                if !progress {
                                    for &id in ids {
                                        if db.local_metadata.maybe_find(&id).is_some() {
                                            *rename_increments.entry(id).or_insert(0) += 1;
                                            progress = true;
                                            break;
                                        }
                                    }
                                }
                                if !progress {
                                    return Err(LbErrKind::Unexpected(format!(
                                        "sync failed to resolve path conflict: {ids:?}"
                                    ))
                                    .into());
                                }
                            }
                            ValidationFailure::SharedLink { link, shared_ancestor } => {
                                // if ancestor is newly shared, delete share; if this device moved
                                // the link, or a folder between it and the share, into the share,
                                // undo that move unless it would land in a deleted folder;
                                // otherwise delete link
                                let mut progress = false;
                                if let Some(base_shared_ancestor) = base.maybe_find(shared_ancestor)
                                {
                                    if !base_shared_ancestor.is_shared()
                                        && files_to_unshare.insert(*shared_ancestor)
                                    {
                                        progress = true;
                                    }
                                }
                                let mut id = *link;
                                while !progress && id != *shared_ancestor {
                                    if let (Some(base_file), Some(remote_file)) =
                                        (base.maybe_find(&id), remote.maybe_find(&id))
                                    {
                                        let from = *remote_file.parent();
                                        let moved_here =
                                            db.local_metadata.maybe_find(&id).is_some()
                                                && local.find(&id)?.parent() != base_file.parent()
                                                && from == *base_file.parent();
                                        if moved_here
                                            && !remote_with_moves.calculate_deleted(&from)?
                                            && files_to_unmove.insert(id)
                                        {
                                            progress = true;
                                        }
                                    }
                                    id = *merge.find(&id)?.parent();
                                }
                                if !progress && links_to_delete.insert(*link) {
                                    progress = true;
                                }
                                if !progress {
                                    return Err(LbErrKind::Unexpected(format!(
                                    "sync failed to resolve shared link: link: {link:?}, shared_ancestor: {shared_ancestor:?}"
                                )).into());
                                }
                            }
                            ValidationFailure::DuplicateLink { target } => {
                                // delete local link with this target
                                let mut progress = false;
                                if let Some(link) = local.linked_by(target)? {
                                    if links_to_delete.insert(link) {
                                        progress = true;
                                    }
                                }
                                if !progress {
                                    return Err(LbErrKind::Unexpected(format!(
                                        "sync failed to resolve duplicate link: target: {target:?}"
                                    ))
                                    .into());
                                }
                            }
                            ValidationFailure::BrokenLink(link) => {
                                // delete local link with this target
                                if !links_to_delete.insert(*link) {
                                    return Err(LbErrKind::Unexpected(format!(
                                        "sync failed to resolve broken link: {link:?}"
                                    ))
                                    .into());
                                }
                            }
                            ValidationFailure::OwnedLink(link) => {
                                // if target is newly owned, unmove target, otherwise delete link
                                let mut progress = false;
                                if let Some(remote_link) = remote.maybe_find(link) {
                                    if let FileType::Link { target } = remote_link.file_type() {
                                        let remote_target = remote.find(&target)?;
                                        if remote_target.owner() != me
                                            && files_to_unmove.insert(target)
                                        {
                                            progress = true;
                                        }
                                    }
                                }
                                if !progress && links_to_delete.insert(*link) {
                                    progress = true;
                                }
                                if !progress {
                                    return Err(LbErrKind::Unexpected(format!(
                                        "sync failed to resolve owned link: {link:?}"
                                    ))
                                    .into());
                                }
                            }
                            ValidationFailure::DuplicateAttachmentsFolder { document } => {
                                // the server's folder stays; this device's new one is replaced by
                                // it
                                let mut existing = None;
                                let mut new = None;
                                for id in merge.ids() {
                                    let file = merge.find(&id)?;
                                    if file.attachment_of().map(|of| of.id) != Some(*document)
                                        || merge.calculate_deleted(&id)?
                                    {
                                        continue;
                                    }
                                    if remote.maybe_find(&id).is_some() {
                                        existing = Some(id);
                                    } else {
                                        new = Some(id);
                                    }
                                }
                                let progress = match (existing, new) {
                                    (Some(existing), Some(new)) => {
                                        replaced_folders.insert(new, existing).is_none()
                                    }
                                    _ => false,
                                };
                                if !progress {
                                    return Err(LbErrKind::Unexpected(format!(
                                        "sync failed to resolve duplicate attachments folders: document: {document:?}"
                                    ))
                                    .into());
                                }
                            }
                            // merge changeset has unexpected validation errors
                            ValidationFailure::Orphan(_)
                            | ValidationFailure::NonFolderWithChildren(_)
                            | ValidationFailure::FileWithDifferentOwnerParent(_)
                            | ValidationFailure::FileNameTooLong(_)
                            | ValidationFailure::DeletedFileUpdated(_)
                            | ValidationFailure::NonDecryptableFileName(_)
                            | ValidationFailure::SelfShare(_)
                            | ValidationFailure::InvalidAttachmentsFolder(_)
                            | ValidationFailure::MisplacedAttachmentsFolder(_) => {
                                validate_result?;
                            }
                        },
                        // merge changeset has unexpected errors
                        _ => {
                            validate_result?;
                        }
                    },
                }
            }
        };

        // base = remote; local = merge
        (&mut db.base_metadata)
            .to_staged(remote_changes.clone())
            .to_lazy()
            .promote()?;
        db.local_metadata.clear()?;
        (&mut db.local_metadata)
            .to_staged(merge_changes)
            .to_lazy()
            .promote()?;

        // todo who else calls this did they manage locks right?
        // self.cleanup_local_metadata()?;
        db.base_metadata.stage(&mut db.local_metadata).prune()?;

        if start.elapsed() > web_time::Duration::from_millis(100) {
            warn!("sync merge held lock for {:?}", start.elapsed());
        }

        Ok(())
    }

    async fn send_pull_events(&self, state: &mut SyncState) -> LbResult<()> {
        if state.new_root.is_some() {
            self.events.signed_in();
        }

        if !state.remote_changes.is_empty() {
            self.events.meta_changed(Actor::Sync);

            let owner = Owner(self.keychain.get_pk()?);
            if state.remote_changes.iter().any(|f| f.owner() != owner) {
                self.events.pending_shares_changed();
            }
        }

        for &doc in &state.pulled_docs {
            self.events.doc_written(doc, Actor::Sync);
        }

        Ok(())
    }

    async fn commit_last_synced(&self, state: &mut SyncState) -> LbResult<()> {
        let mut tx = self.begin_tx().await;
        let db = tx.db();
        db.last_synced.replace(state.updates_as_of as i64)?;

        if let Some(root) = state.new_root {
            db.root.replace(root)?;
        }

        Ok(())
    }

    async fn populate_pk_cache(&self) -> LbResult<()> {
        // todo: is this the move?
        let mut missing_owners = HashSet::new();
        {
            let tx = self.ro_tx().await;
            let db = tx.db();
            for file in db.base_metadata.iter().map(|(_, value)| value) {
                for user_access_key in file.user_access_keys() {
                    let enc_by = Owner(user_access_key.encrypted_by);
                    let enc_for = Owner(user_access_key.encrypted_for);

                    if !db.pub_key_lookup.contains_key(&enc_by) {
                        missing_owners.insert(enc_by);
                    }

                    if !db.pub_key_lookup.contains_key(&enc_for) {
                        missing_owners.insert(enc_for);
                    }
                }
            }
        }

        let mut new_owners = HashMap::new();
        {
            for owner in missing_owners {
                let username_result = self
                    .client
                    .get_username(self.get_account().unwrap(), GetUsernameRequest { key: owner.0 })
                    .await;
                new_owners.insert(owner, username_result);
            }
        }

        let mut tx = self.begin_tx().await;
        let db = tx.db();

        let have_updates = !new_owners.is_empty();
        for (owner, username) in new_owners {
            let username = match username {
                Err(ApiError::Endpoint(GetUsernameError::UserNotFound)) => "<unknown>".to_string(),
                Ok(username) => username.username,
                _ => continue, // todo: possibly add some logging here
            };

            db.pub_key_lookup.insert(owner, username).unwrap();
        }

        if have_updates {
            self.events.meta_changed(Actor::Sync);
        }

        Ok(())
    }

    /// Updates remote and base metadata to local.
    async fn push_meta(&self) -> LbResult<()> {
        let mut updates = vec![];
        let mut local_changes_no_digests = Vec::new();

        let tx = self.ro_tx().await;
        let db = tx.db();

        // remote = local
        let local = db.base_metadata.stage(&db.local_metadata).to_lazy();

        for id in local.tree.staged.ids() {
            let mut local_change = local.tree.staged.find(&id)?.timestamped_value.value.clone();
            let maybe_base_file = local.tree.base.maybe_find(&id);

            // change everything but document hmac and re-sign
            local_change.set_hmac_and_size(
                maybe_base_file.and_then(|f| f.document_hmac().copied()),
                maybe_base_file.and_then(|f| *f.timestamped_value.value.doc_size()),
            );
            let local_change = local_change.sign(&self.keychain)?;

            local_changes_no_digests.push(local_change.clone());
            let file_diff = FileDiff { old: maybe_base_file.cloned(), new: local_change };
            updates.push(file_diff);
        }

        drop(tx);

        if !updates.is_empty() {
            self.client
                .upsert_file_metadata_v2(
                    self.get_account()?,
                    UpsertRequestV2 { updates: updates.clone() },
                )
                .await?;
        }

        let mut tx = self.begin_tx().await;
        let db = tx.db();

        // base = local
        promote_pushed(&mut db.base_metadata, &mut db.local_metadata, local_changes_no_digests)?;

        tx.end();

        Ok(())
    }

    /// Updates remote and base files to local. Assumes metadata is already pushed for all new files.
    // todo: make this so that all document updates are attempted and we don't just return the
    // first error. Once an attempt is made we can return any or all errors, either would be an
    // improvement
    async fn push_docs(&self) -> LbResult<()> {
        let mut updates = vec![];
        let mut local_changes_digests_only = vec![];

        let tx = self.ro_tx().await;
        let db = tx.db();
        let start = Instant::now();

        let local = db.base_metadata.stage(&db.local_metadata).to_lazy();

        for id in local.tree.staged.ids() {
            let base_file = local.tree.base.find(&id)?.clone();

            // change only document hmac and re-sign
            let mut local_change = base_file.timestamped_value.value.clone();
            local_change.set_hmac_and_size(
                local.find(&id)?.document_hmac().copied(),
                *local.find(&id)?.timestamped_value.value.doc_size(),
            );

            if base_file.document_hmac() == local_change.document_hmac()
                || local_change.document_hmac().is_none()
            {
                continue;
            }

            let local_change = local_change.sign(&self.keychain)?;

            updates.push(FileDiff { old: Some(base_file), new: local_change.clone() });
            local_changes_digests_only.push(local_change);
            self.events
                .sync_update(SyncIncrement::PushingDocument(id, true));
        }

        drop(tx);
        if start.elapsed() > web_time::Duration::from_millis(100) {
            warn!("sync push_docs held lock for {:?}", start.elapsed());
        }

        let futures = updates.clone().into_iter().map(|diff| self.push_doc(diff));

        let mut stream = stream::iter(futures).buffer_unordered(
            thread::available_parallelism()
                .unwrap_or(NonZeroUsize::new(4).unwrap())
                .into(),
        );

        let mut docs_without_errors = vec![];
        let mut last_error: Option<LbErr> = None;

        while let Some(fut) = stream.next().await {
            match fut {
                Ok(id) => {
                    docs_without_errors.push(id);
                    self.events
                        .sync_update(SyncIncrement::PushingDocument(id, false));
                }
                Err(err) => {
                    last_error = Some(err);
                }
            }
        }

        local_changes_digests_only.retain(|f| docs_without_errors.contains(f.id()));

        let mut tx = self.begin_tx().await;
        let db = tx.db();
        // base = local (metadata)
        promote_pushed(&mut db.base_metadata, &mut db.local_metadata, local_changes_digests_only)?;

        tx.end();

        if let Some(err) = last_error { Err(err) } else { Ok(()) }
    }

    async fn push_doc(&self, diff: FileDiff<SignedMeta>) -> LbResult<Uuid> {
        let id = *diff.new.id();
        let hmac = diff.new.document_hmac();
        let hmac = *hmac.ok_or(LbErrKind::FileNonexistent)?;
        let local_document_change = self.docs.get(id, hmac).await?;
        self.client
            .change_doc_v2(
                self.get_account()?,
                ChangeDocRequestV2 { diff, new_content: local_document_change },
            )
            .await?;

        Ok(id)
    }

    #[cfg(not(target_family = "wasm"))]
    async fn send_debug_info(&self, account: Account) {
        use crate::service::debug;

        let max_panic_time = debug::latest_panic_time(&self.config.writeable_path)
            .await
            .unwrap_or_else(|e| {
                warn!("could not enumerate panic files: {e:?}");
                None
            });

        let last_sent = {
            let tx = self.ro_tx().await;
            tx.db().last_extracted_panic.as_ref().copied()
        };

        let should_send = match (last_sent, max_panic_time) {
            (None, _) => true,
            (Some(prev), Some(cur)) => cur > prev,
            (Some(_), None) => false,
        };

        if !should_send {
            return;
        }

        let debug_info = match self.debug_info(false).await {
            Ok(debug_info) => debug_info,
            Err(e) => {
                warn!("could not collect debug_info: {e:?}");
                return;
            }
        };

        let new_marker = max_panic_time.unwrap_or(0);
        let bg_self = self.clone();
        let task = async move {
            match bg_self
                .client
                .upsert_debug_info(&account, UpsertDebugInfoRequest { debug_info })
                .await
            {
                Ok(_) => {
                    let mut tx = bg_self.begin_tx().await;
                    if let Err(e) = tx.db().last_extracted_panic.replace(new_marker) {
                        warn!("could not record last_extracted_panic: {e:?}");
                    }
                    tx.end();
                }
                Err(e) => warn!("send_debug_info failed: {e:?}"),
            }
        };

        if self.config.background_work {
            tokio::spawn(task);
        } else {
            task.await;
        }
    }

    async fn read_document_helper<T>(
        &self, id: Uuid, tree: &mut LazyTree<T>,
    ) -> LbResult<DecryptedDocument>
    where
        T: TreeLike<F = SignedMeta>,
    {
        let file = tree.find(&id)?;
        validate::is_document(file)?;
        let hmac = file.document_hmac().copied();

        let doc = match hmac {
            Some(hmac) => {
                let doc = self.docs.get(id, hmac).await?;
                tree.decrypt_document(&id, &doc, &self.keychain)?
            }
            None => vec![],
        };

        Ok(doc)
    }

    /// for tests only
    #[doc(hidden)]
    pub async fn server_dirty_ids(&self) -> LbResult<Vec<Uuid>> {
        let mut state = self.syncer.lock().await;
        #[cfg(not(any(target_family = "wasm", target_os = "ios")))]
        let _sync_lock = self.lock_sync()?;
        self.inital_sync_state(&mut state).await?;
        self.process_deletions().await?;
        self.fetch_meta(&mut state).await?;

        let server_ids = state.remote_changes.iter().map(|f| *f.id()).collect();

        Ok(server_ids)
    }

    pub(crate) fn setup_syncer(&self) {
        if self.config.background_work {
            self.clone().local_change_worker();
            self.clone().periodic_sync_worker();
            self.clone().post_sync_worker();
        }
    }

    fn local_change_worker(self) {
        #[cfg(not(target_family = "wasm"))]
        tokio::spawn(async move {
            let mut events = self.subscribe();

            let sync_criteria = |e: Event| {
                matches!(
                    e,
                    Event::MetadataChanged(Actor::User(_))
                        | Event::DocumentWritten(_, Actor::User(_))
                )
            };

            loop {
                time::sleep(Duration::from_millis(500)).await;
                let mut should_sync = false;

                // drain the current channel, so we don't sync for each keystroke if they pile up
                loop {
                    match events.try_recv() {
                        Ok(event) => should_sync |= sync_criteria(event),
                        Err(TryRecvError::Empty) => break,
                        Err(TryRecvError::Lagged(_)) => should_sync |= self.has_local_work().await,
                        Err(TryRecvError::Closed) => return,
                    }
                }

                // empty channel + nothing interesting has happened, sit and wait for something
                // interesting
                if !should_sync {
                    should_sync = match events.recv().await {
                        Ok(event) => sync_criteria(event),
                        Err(RecvError::Lagged(_)) => self.has_local_work().await,
                        Err(RecvError::Closed) => return,
                    };
                }

                if should_sync {
                    self.sync().await.map_unexpected().log_and_ignore();
                }
            }
        });
    }

    /// Whether a sync would push anything: what a missed event changed is still unsynced.
    #[cfg(not(target_family = "wasm"))]
    async fn has_local_work(&self) -> bool {
        !self.local_changes().await.is_empty()
    }

    fn periodic_sync_worker(self) {
        #[cfg(not(target_family = "wasm"))]
        tokio::spawn(async move {
            loop {
                if self.user_active().await {
                    tokio::time::sleep(Duration::from_secs(3)).await;
                } else {
                    tokio::select! {
                        _ = tokio::time::sleep(Duration::from_secs(5 * 60)) => {}
                        _ = self.user_wake.notified() => {}
                    }
                }
                self.sync().await.map_unexpected().log_and_ignore();
            }
        });
    }

    pub(crate) async fn user_active(&self) -> bool {
        let last_seen = self.user_last_seen.read().await;
        last_seen.elapsed() < Duration::from_secs(15)
    }

    fn post_sync_worker(self) {
        #[cfg(not(target_family = "wasm"))]
        tokio::spawn(async move {
            let mut events = self.subscribe();

            loop {
                // A receiver that lagged missed a sync's worth of events, a `SyncFinished`
                // possibly among them; the work after a sync is idempotent, so it runs again.
                match events.recv().await {
                    Ok(Event::Sync(SyncIncrement::SyncFinished(_))) | Err(RecvError::Lagged(_)) => {
                        self.fetcher().await.map_unexpected().log_and_ignore();
                        self.populate_pk_cache()
                            .await
                            .map_unexpected()
                            .log_and_ignore();
                    }
                    Ok(_) => {}
                    Err(RecvError::Closed) => return,
                }
            }
        });
    }

    async fn fetcher(&self) -> LbResult<()> {
        let mut files_to_pull = vec![];

        let tx = self.ro_tx().await;
        let db = tx.db();

        let Some(root) = db.root.as_ref() else {
            return Ok(());
        };

        // we can only fetch things we know the server knows about
        let mut tree = db.base_metadata.stage(None).to_lazy();

        for id in tree.descendants_using_links(root)? {
            let file = tree.find(&id)?;
            let hmac = file.document_hmac().copied();

            // skip non-documents
            if !file.is_document() {
                continue;
            }

            // skip deleted files
            if tree.calculate_deleted(&id)? {
                continue;
            }

            if hmac.is_some_and(|hmac| self.docs.exists(id, hmac)) {
                continue;
            }

            // skip non-first-party files
            let name = tree.name(&id, &self.keychain)?;
            if !name.ends_with(".md") && !name.ends_with(".svg") {
                continue;
            }

            files_to_pull.push((id, hmac));
        }

        drop(tx);

        // this could all be done in parallel, but for now going to not do it that way
        // benefits: less work, but also ensures that a file that needs to be fetched immediately
        // can be
        for (id, hmac) in files_to_pull {
            if let Some(hmac) = hmac {
                self.ensure_doc_available(id, hmac).await?;
            }
        }

        Ok(())
    }
}

/// Whether this device may still change `id` or what's in it: write is granted at the nearest file
/// `remote` has, at or above `id` in this device's tree, by a share this device hasn't declined,
/// and in this device's own tree. `remote` is the server's tree, with this device's kept moves
/// applied once they are, so shares are read where each file ends up, not the merge's.
fn may_write_in<L: TreeLike, R: TreeLike<F = L::F>>(
    local: &LazyTree<L>, remote: &LazyTree<R>, me: Owner, id: &Uuid,
) -> LbResult<bool> {
    if local.maybe_find(id).is_some()
        && local_access(local, remote, me, id)? < Some(UserAccessMode::Write)
    {
        return Ok(false);
    }
    let mut id = *id;
    while remote.maybe_find(&id).is_none() {
        let Some(file) = local.maybe_find(&id) else {
            return Ok(false);
        };
        if file.parent() == file.id() {
            return Ok(false);
        }
        id = *file.parent();
    }
    Ok(server_access(local, remote, me, &id)? >= Some(UserAccessMode::Write))
}

/// This device's access to `id`: what its own tree grants, or more where the server's tree grants
/// more. The server's tree counts for `id` and each folder above it that the server places
/// differently, because that is where the file will end up:
/// - this device no longer has the folder's parent, as after losing a share;
/// - the server has the folder under another parent, as when this device moved it into a shared
///   folder that has since become read-only, and the move is about to be undone.
fn local_access<L: TreeLike, R: TreeLike<F = L::F>>(
    local: &LazyTree<L>, remote: &LazyTree<R>, me: Owner, id: &Uuid,
) -> LbResult<Option<UserAccessMode>> {
    let mut mode = local.access_mode(me, id)?;
    for id in local.access_sources(id)? {
        let file = local.find(&id)?;
        if file.is_root() {
            continue;
        }
        if let Some(placed) = remote.maybe_find(&id) {
            let elsewhere =
                local.maybe_find(file.parent()).is_none() || placed.parent() != file.parent();
            if elsewhere && remote.maybe_find(placed.parent()).is_some() {
                mode = mode.max(server_access(local, remote, me, placed.parent())?);
            }
        }
    }
    Ok(mode)
}

/// The server's access at `id`, which `remote` has, less the shares this device declined.
fn server_access<L: TreeLike, R: TreeLike<F = L::F>>(
    local: &LazyTree<L>, remote: &LazyTree<R>, me: Owner, id: &Uuid,
) -> LbResult<Option<UserAccessMode>> {
    let mut mode = None;
    for id in remote.access_sources(id)? {
        let declined = local.maybe_find(&id).is_some_and(|file| {
            file.user_access_keys()
                .iter()
                .any(|key| key.encrypted_for == me.0 && key.deleted)
        });
        if !declined {
            mode = mode.max(remote.find(&id)?.access_mode(&me));
        }
    }
    Ok(mode)
}

/// Promotes `pushed` into `base`, keeping local writes made during the push.
fn promote_pushed<B, L>(base: &mut B, local: &mut L, pushed: Vec<SignedMeta>) -> LbResult<()>
where
    B: TreeLikeMut<F = SignedMeta>,
    L: TreeLikeMut<F = SignedMeta>,
{
    // a local write can happen between push and promote
    let local_files = {
        let tree = base.stage(&*local);
        pushed
            .iter()
            .map(|f| tree.find(f.id()).cloned())
            .collect::<LbResult<Vec<_>>>()?
    };
    base.to_lazy().stage(pushed).promote()?;
    // this ensures those writes are not lost when the push is promoted
    for file in local_files {
        local.insert(file)?;
    }
    base.stage(local).prune()
}

/// Undoes this device's moves that form a cycle, or fails when none of them is this device's.
/// An attachments folder in the cycle is there because of its document's place, so its
/// document's move is undone too; otherwise repair would move the folder back into the cycle.
fn unmove_cycle<L: TreeLike, T: TreeLike>(
    local: &L, local_changes: &T, ids: &HashSet<Uuid>, files_to_unmove: &mut HashSet<Uuid>,
) -> LbResult<()> {
    let mut progress = false;
    for &id in ids {
        let mut moved = vec![id];
        if let Some(of) = local.maybe_find(&id).and_then(|f| f.attachment_of()) {
            moved.push(of.id);
        }
        for id in moved {
            if local_changes.maybe_find(&id).is_some() && files_to_unmove.insert(id) {
                progress = true;
            }
        }
    }
    if !progress {
        return Err(LbErrKind::Unexpected(format!("sync failed to resolve cycle: {ids:?}")).into());
    }
    Ok(())
}

/// `ids` ordered so each file comes after its ancestors that are also in `ids`.
fn parents_first<T: TreeLike>(tree: &LazyTree<T>, ids: &HashSet<Uuid>) -> LbResult<Vec<Uuid>> {
    let mut order = Vec::with_capacity(ids.len());
    let mut walked = HashSet::with_capacity(ids.len());
    for &id in ids {
        let mut unwalked_ancestry = Vec::new();
        let mut id = id;
        while walked.insert(id) {
            unwalked_ancestry.push(id);
            let Some(file) = tree.maybe_find(&id) else { break };
            id = *file.parent();
        }
        order.extend(
            unwalked_ancestry
                .into_iter()
                .rev()
                .filter(|id| ids.contains(id)),
        );
    }
    Ok(order)
}

/// An attachments folder's document's parent, or a conflicting file's replacement parent, or a
/// normal file's normal parent
fn created_parent<T: TreeLike<F = SignedMeta>>(
    tree: &LazyTree<T>, file: &SignedMeta, replaced_folders: &HashMap<Uuid, Uuid>,
) -> Uuid {
    match tree.maybe_find_attached(file) {
        Some(document) => *document.parent(),
        None => replacement(replaced_folders, file.parent()),
    }
}

/// `folder`, or the folder that replaces it.
fn replacement(replaced_folders: &HashMap<Uuid, Uuid>, folder: &Uuid) -> Uuid {
    *replaced_folders.get(folder).unwrap_or(folder)
}

/// A creation whose parent is in neither the tree nor the creations before it.
fn orphaned_creation(id: Uuid) -> impl FnOnce(LbErr) -> LbErr {
    move |err| match err.kind {
        LbErrKind::FileParentNonexistent => LbErrKind::Unexpected(format!(
            "sync failed to find a topological order for file creation {id}"
        ))
        .into(),
        _ => err,
    }
}

/// A file this device has no access to, e.g. inside a share it declined. A share root carrying
/// this device's own (possibly tombstoned) key is not lost: that tombstone is what gets pushed.
fn lost_access<L: TreeLike, R: TreeLike<F = L::F>>(
    local: &LazyTree<L>, remote: &LazyTree<R>, me: Owner, id: &Uuid,
) -> LbResult<bool> {
    let is_my_share_root = local
        .find(id)?
        .user_access_keys()
        .iter()
        .any(|k| k.encrypted_for == me.0);
    let reachable = local_access(local, remote, me, id)?.is_some();
    Ok(!is_my_share_root && !reachable)
}

/// Each recipient's share of a file as (mode, deleted); a file keeps one share per recipient.
fn shares_by_recipient(file: Option<&SignedMeta>) -> HashMap<Owner, (UserAccessMode, bool)> {
    file.into_iter()
        .flat_map(|file| file.user_access_keys())
        .map(|key| (Owner(key.encrypted_for), (key.mode, key.deleted)))
        .collect()
}