brume-daemon 0.1.0

A daemon that synchronizes files in the background using Brume
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
use std::{any::Any, collections::HashMap, sync::Arc, thread::sleep, time::Duration};

use brume::{
    concrete::{
        FSBackend, FsBackendError, Named,
        local::{LocalDir, LocalSyncInfo},
        nextcloud::{NextcloudFs, NextcloudSyncInfo},
    },
    filesystem::FileSystem,
    synchro::{ConflictResolutionState, FullSyncStatus, Synchro, SynchroSide},
    vfs::{Vfs, VirtualPath},
};
use futures::{StreamExt, future::join_all, stream};
use log::{debug, error, info};
use serde::Serialize;
use thiserror::Error;
use tokio::sync::{Mutex, RwLock, RwLockReadGuard};
use uuid::Uuid;

use brume_daemon_proto::{
    AnyFsCreationInfo, AnyFsDescription, AnyFsRef, AnySynchroCreationInfo, AnySynchroRef,
    SynchroId, SynchroState, SynchroStatus,
};

use crate::db::{Database, DatabaseError};

#[derive(Error, Debug)]
pub enum SyncError {
    #[error("Error during sync process")]
    SyncFailed(#[from] SynchroFailed),
    #[error("Invalid synchro")]
    InvalidSynchroState(#[from] InvalidSynchro),
    #[error("Synchro not found: {0:?}")]
    SynchroNotFound(SynchroId),
    #[error("Database error")]
    Database(#[from] DatabaseError),
}

#[derive(Error, Debug)]
#[error("Failed to synchronize {synchro}")]
pub struct SynchroFailed {
    synchro: AnySynchroRef,
    source: brume::Error,
}

#[derive(Error, Debug)]
#[error("Synchro in invalid state: {synchro}")]
pub struct InvalidSynchro {
    synchro: AnySynchroRef,
}

impl From<AnySynchroRef> for InvalidSynchro {
    fn from(value: AnySynchroRef) -> Self {
        InvalidSynchro { synchro: value }
    }
}

#[derive(Error, Debug)]
pub enum SynchroCreationError {
    #[error("The filesystems are already synchronized")]
    AlreadyPresent,
    #[error("Failed to instantiate filesystem object")]
    FileSystemCreationError(#[from] FsBackendError),
    #[error("The provided synchro is not of the expected type")]
    InvalidType { expected: String, found: String },
}

impl SynchroCreationError {
    fn invalid_type<Expected: Named, Found: Named>() -> Self {
        Self::InvalidType {
            expected: Expected::TYPE_NAME.to_string(),
            found: Found::TYPE_NAME.to_string(),
        }
    }
}

#[derive(Error, Debug)]
pub enum SynchroDeletionError {
    #[error("Invalid synchro")]
    InvalidSynchroState(#[from] InvalidSynchro),
    #[error("Synchro not found: {0:?}")]
    SynchroNotFound(SynchroId),
}

#[derive(Error, Debug)]
pub enum SynchroModificationError {
    #[error("Invalid synchro")]
    InvalidSynchroState(#[from] InvalidSynchro),
    #[error("Synchro not found: {0:?}")]
    SynchroNotFound(SynchroId),
}

/// Result of a synchro creation
#[derive(Clone)]
pub struct CreatedSynchro {
    id: SynchroId,
    name: String,
    local_id: Uuid,
    remote_id: Uuid,
}

impl CreatedSynchro {
    pub fn id(&self) -> SynchroId {
        self.id
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn local_id(&self) -> Uuid {
        self.local_id
    }

    pub fn remote_id(&self) -> Uuid {
        self.remote_id
    }
}

/// A [`SynchroList`] that allows only read-only access.
///
/// The list content cannot be modified, but since the underlying [`FileSystems`] are locked behind
/// mutexes, they are themselves modifiabled.
///
/// [`FileSystems`]: FileSystem
#[derive(Clone)]
pub struct ReadOnlySynchroList {
    maps: Arc<RwLock<SynchroList>>,
}

impl ReadOnlySynchroList {
    pub async fn read(&self) -> RwLockReadGuard<SynchroList> {
        self.maps.read().await
    }

    pub async fn len(&self) -> usize {
        self.read().await.len()
    }

    pub async fn is_empty(&self) -> bool {
        self.len().await == 0
    }
}

/// A synchronized Filesystem pair where both filesystems are in a Mutex
struct SynchroMutex<
    'local,
    'remote,
    LocalBackend: FSBackend + 'static,
    RemoteBackend: FSBackend + 'static,
> {
    local: &'local Mutex<FileSystem<LocalBackend>>,
    remote: &'remote Mutex<FileSystem<RemoteBackend>>,
}

/// Allow to easily convert the given type into [`Any`] for runtime downcast
trait DynTyped {
    fn as_any(&self) -> &dyn Any;
}

impl<T: FSBackend + 'static> DynTyped for Mutex<FileSystem<T>> {
    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// Holds a list of pair of [`FileSystems`] that can be synchronized using [`Synchro::full_sync`].
///
/// The filesystems can be any of the [`supported types`]
///
/// [`FileSystems`]: FileSystem
/// [`supported types`]: brume_daemon_proto::AnyFsCreationInfo
#[derive(Default)]
pub struct SynchroList {
    synchros: HashMap<SynchroId, RwLock<AnySynchroRef>>,
    nextcloud_list: HashMap<Uuid, Mutex<FileSystem<NextcloudFs>>>,
    local_dir_list: HashMap<Uuid, Mutex<FileSystem<LocalDir>>>,
}

impl SynchroList {
    /// Create a new empty list
    pub fn new() -> Self {
        Self::default()
    }

    pub fn len(&self) -> usize {
        self.synchros.len()
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn synchro_ref_list(&self) -> &HashMap<SynchroId, RwLock<AnySynchroRef>> {
        &self.synchros
    }

    pub(crate) fn synchro_ref_list_mut(
        &mut self,
    ) -> &mut HashMap<SynchroId, RwLock<AnySynchroRef>> {
        &mut self.synchros
    }

    fn create_and_insert_fs(
        &mut self,
        fs_info: AnyFsCreationInfo,
    ) -> Result<AnyFsRef, FsBackendError> {
        let fs_ref: AnyFsRef = fs_info.clone().into();
        match fs_info {
            AnyFsCreationInfo::LocalDir(info) => {
                let concrete = info.try_into()?;
                self.local_dir_list
                    .insert(fs_ref.id(), Mutex::new(FileSystem::new(concrete)));
                Ok(fs_ref)
            }
            AnyFsCreationInfo::Nextcloud(info) => {
                let concrete = info.try_into()?;
                self.nextcloud_list
                    .insert(fs_ref.id(), Mutex::new(FileSystem::new(concrete)));
                Ok(fs_ref)
            }
        }
    }

    pub(crate) fn insert_existing_fs<SyncInfo: Named + 'static>(
        &mut self,
        fs_info: AnyFsCreationInfo,
        vfs: &Vfs<SyncInfo>,
        id: Uuid,
    ) -> Result<(), SynchroCreationError> {
        match fs_info {
            AnyFsCreationInfo::LocalDir(info) => {
                let concrete = info.try_into().map_err(FsBackendError::from)?;
                let mut fs = FileSystem::new(concrete);
                *fs.vfs_mut() = (vfs as &dyn Any)
                    .downcast_ref::<Vfs<LocalSyncInfo>>()
                    .ok_or_else(|| SynchroCreationError::invalid_type::<LocalSyncInfo, SyncInfo>())?
                    .clone();
                self.local_dir_list.insert(id, Mutex::new(fs));
                Ok(())
            }
            AnyFsCreationInfo::Nextcloud(info) => {
                let concrete = info.try_into().map_err(FsBackendError::from)?;
                let mut fs = FileSystem::new(concrete);
                *fs.vfs_mut() = (vfs as &dyn Any)
                    .downcast_ref::<Vfs<NextcloudSyncInfo>>()
                    .ok_or_else(|| {
                        SynchroCreationError::invalid_type::<NextcloudSyncInfo, SyncInfo>()
                    })?
                    .clone();
                self.nextcloud_list.insert(id, Mutex::new(fs));
                Ok(())
            }
        }
    }

    /// Checks if the two Filesystems in the pair are already synchronized together.
    pub async fn is_synchronized(
        &self,
        local_desc: &AnyFsDescription,
        remote_desc: &AnyFsDescription,
    ) -> bool {
        for sync in self.synchros.values() {
            let sync = sync.read().await;
            if (sync.local().description() == local_desc
                || sync.local().description() == remote_desc)
                && (sync.remote().description() == local_desc
                    || sync.remote().description() == remote_desc)
            {
                return true;
            }
        }

        false
    }

    async fn name_is_unique(&self, name: &str) -> bool {
        for sync in self.synchros.values() {
            if sync.read().await.name() == name {
                return false;
            }
        }
        true
    }

    async fn make_unique_name(&self, name: &str) -> String {
        if self.name_is_unique(name).await {
            return name.to_string();
        }

        let mut counter = 1;
        loop {
            let new_name = format!("{}{}", name, counter);
            if self.name_is_unique(name).await {
                return new_name;
            }
            counter += 1;
        }
    }

    /// Generates a unique and simple name for a synchro, based on the name of the remote and local
    /// fs
    async fn unique_synchro_name(&self, local_name: &str, remote_name: &str) -> String {
        let same_remote: Vec<_> = stream::iter(self.synchros.values())
            .filter(|sync| async { sync.read().await.remote().name() == remote_name })
            .collect()
            .await;

        if same_remote.is_empty() && self.name_is_unique(remote_name).await {
            return remote_name.to_string();
        }

        let same_local: Vec<_> = stream::iter(same_remote)
            .filter(|sync| async { sync.read().await.local().name() == local_name })
            .collect()
            .await;

        let name = format!("{local_name}-{remote_name}");
        if same_local.is_empty() && self.name_is_unique(&name).await {
            return name;
        }

        self.make_unique_name(&name).await
    }

    /// Creates and inserts a new filesystem Synchro in the list
    pub async fn insert(
        &mut self,
        sync_info: AnySynchroCreationInfo,
    ) -> Result<CreatedSynchro, SynchroCreationError> {
        let local_desc = sync_info.local().clone().into();
        let remote_desc = sync_info.remote().clone().into();

        if self.is_synchronized(&local_desc, &remote_desc).await {
            return Err(SynchroCreationError::AlreadyPresent);
        }
        let id = SynchroId::new();

        let local_ref = self.create_and_insert_fs(sync_info.local().clone())?;
        let remote_ref = self.create_and_insert_fs(sync_info.remote().clone())?;
        let name = if let Some(name) = sync_info.name() {
            self.make_unique_name(name).await
        } else {
            self.unique_synchro_name(local_ref.name(), remote_ref.name())
                .await
        };

        info!("Synchro created: name: {name}, id: {id:?}");
        let res = CreatedSynchro {
            id,
            name: name.clone(),
            local_id: local_ref.id(),
            remote_id: remote_ref.id(),
        };

        let synchro = AnySynchroRef::new(local_ref, remote_ref, name);

        self.synchros.insert(id, RwLock::new(synchro.clone()));

        Ok(res)
    }

    /// Deletes a synchronization from the list
    pub fn remove(&mut self, id: SynchroId) -> Result<(), SynchroDeletionError> {
        if let Some(sync) = self.synchros.remove(&id) {
            let mut res = Ok(());
            let sync = sync.into_inner();

            if !self.remove_fs(sync.local()) {
                res = Err(SynchroDeletionError::InvalidSynchroState(
                    sync.clone().into(),
                ));
            }
            if !self.remove_fs(sync.remote()) {
                res = Err(SynchroDeletionError::InvalidSynchroState(
                    sync.clone().into(),
                ));
            }

            info!("Synchro deleted: {id:?}");
            res
        } else {
            Err(SynchroDeletionError::SynchroNotFound(id))
        }
    }

    pub async fn resolve_conflict(
        &self,
        id: SynchroId,
        path: &VirtualPath,
        side: SynchroSide,
        db: &Database,
    ) -> Result<(), SyncError> {
        let synchro = self
            .synchros
            .get(&id)
            .ok_or_else(|| SyncError::SynchroNotFound(id))?;
        let local_desc = synchro.read().await.local().description().clone();
        let remote_desc = synchro.read().await.remote().description().clone();
        match (local_desc, remote_desc) {
            (AnyFsDescription::LocalDir(_), AnyFsDescription::LocalDir(_)) => {
                self.resolve_conflict_sync::<LocalDir, LocalDir>(id, synchro, path, side, db)
                    .await
            }
            (AnyFsDescription::LocalDir(_), AnyFsDescription::Nextcloud(_)) => {
                self.resolve_conflict_sync::<LocalDir, NextcloudFs>(id, synchro, path, side, db)
                    .await
            }
            (AnyFsDescription::Nextcloud(_), AnyFsDescription::LocalDir(_)) => {
                self.resolve_conflict_sync::<NextcloudFs, LocalDir>(id, synchro, path, side, db)
                    .await
            }
            (AnyFsDescription::Nextcloud(_), AnyFsDescription::Nextcloud(_)) => {
                self.resolve_conflict_sync::<NextcloudFs, NextcloudFs>(id, synchro, path, side, db)
                    .await
            }
        }
    }

    fn get_fs<Backend: FSBackend + 'static>(
        &self,
        fs: &AnyFsRef,
    ) -> Option<&Mutex<FileSystem<Backend>>> {
        match fs.description() {
            AnyFsDescription::LocalDir(_) => self
                .local_dir_list
                .get(&fs.id())
                .and_then(|fs| fs.as_any().downcast_ref::<Mutex<FileSystem<Backend>>>()),
            AnyFsDescription::Nextcloud(_) => self
                .nextcloud_list
                .get(&fs.id())
                .and_then(|fs| fs.as_any().downcast_ref::<Mutex<FileSystem<Backend>>>()),
        }
    }

    fn remove_fs(&mut self, fs: &AnyFsRef) -> bool {
        match fs.description() {
            AnyFsDescription::LocalDir(_) => self.local_dir_list.remove(&fs.id()).is_some(),
            AnyFsDescription::Nextcloud(_) => self.nextcloud_list.remove(&fs.id()).is_some(),
        }
    }

    fn get_sync<LocalBackend: FSBackend + 'static, RemoteBackend: FSBackend + 'static>(
        &self,
        synchro: &AnySynchroRef,
    ) -> Option<SynchroMutex<LocalBackend, RemoteBackend>> {
        let local = self.get_fs::<LocalBackend>(synchro.local())?;
        let remote = self.get_fs::<RemoteBackend>(synchro.remote())?;

        Some(SynchroMutex { local, remote })
    }

    /// Resolves a conflict on a synchro in the list by applying the update from the chose side
    pub async fn resolve_conflict_sync<
        LocalBackend: FSBackend + 'static,
        RemoteBackend: FSBackend + 'static,
    >(
        &self,
        id: SynchroId,
        synchro_lock: &RwLock<AnySynchroRef>,
        path: &VirtualPath,
        side: SynchroSide,
        db: &Database,
    ) -> Result<(), SyncError>
    where
        LocalBackend::SyncInfo: Serialize,
        RemoteBackend::SyncInfo: Serialize,
    {
        // Wait for synchro to be ready
        loop {
            {
                let mut synchro = synchro_lock.write().await;

                if synchro.status().is_synchronizable() {
                    let status = SynchroStatus::SyncInProgress;
                    synchro.set_status(status);
                    db.set_synchro_status(id, status).await?;
                    break;
                }
            }
            sleep(Duration::from_secs(1)); // TODO: make configurable
        }

        let res = {
            let synchro = synchro_lock.read().await;

            let synchro_mutex = self
                .get_sync::<LocalBackend, RemoteBackend>(&synchro)
                .ok_or_else(|| InvalidSynchro::from(synchro.clone()))
                .unwrap();

            let mut local_fs = synchro_mutex.local.lock().await;
            let mut remote_fs = synchro_mutex.remote.lock().await;

            let mut sync: Synchro<'_, '_, LocalBackend, RemoteBackend> =
                Synchro::new(&mut local_fs, &mut remote_fs);
            sync.resolve_conflict(path, side).await
        };

        match res {
            Ok(conflict_result) => {
                let status = conflict_result.status().into();
                synchro_lock.write().await.set_status(status);
                db.set_synchro_status(id, status).await?;

                match conflict_result.state() {
                    ConflictResolutionState::Local(node_state) => {
                        db.update_vfs_node_state(
                            synchro_lock.read().await.local().id(),
                            path,
                            node_state,
                        )
                        .await?
                    }
                    ConflictResolutionState::Remote(node_state) => {
                        db.update_vfs_node_state(
                            synchro_lock.read().await.remote().id(),
                            path,
                            node_state,
                        )
                        .await?
                    }
                    ConflictResolutionState::None => {
                        db.delete_vfs_node(synchro_lock.read().await.local().id(), path)
                            .await?
                    }
                }
                Ok(())
            }

            Err(err) => {
                let mut synchro = synchro_lock.write().await;
                let status = FullSyncStatus::from(&err).into();
                synchro.set_status(status);
                db.set_synchro_status(id, status).await?;
                Err(SynchroFailed {
                    synchro: synchro.to_owned(),
                    source: err,
                }
                .into())
            }
        }
    }

    /// Performs a [`full_sync`] on the provided synchro, that should be in the list
    ///
    /// [`full_sync`]: brume::synchro::Synchro::full_sync
    pub async fn sync_one<LocalBackend: FSBackend + 'static, RemoteBackend: FSBackend + 'static>(
        &self,
        id: SynchroId,
        synchro_lock: &RwLock<AnySynchroRef>,
        db: &Database,
    ) -> Result<(), SyncError>
    where
        LocalBackend::SyncInfo: Serialize,
        RemoteBackend::SyncInfo: Serialize,
    {
        {
            let mut synchro = synchro_lock.write().await;

            // Skip synchro that are already identified as desynchronized until the user fixes it
            if !synchro.status().is_synchronizable() {
                return Ok(());
            }
            let status = SynchroStatus::SyncInProgress;
            synchro.set_status(status);
            db.set_synchro_status(id, status).await?;
        }

        let res = {
            let synchro = synchro_lock.read().await;
            debug!("Starting full_sync for Synchro {}", synchro.name());

            let synchro_mutex = self
                .get_sync::<LocalBackend, RemoteBackend>(&synchro)
                .ok_or_else(|| InvalidSynchro::from(synchro.clone()))?;

            let mut local_fs = synchro_mutex.local.lock().await;
            let mut remote_fs = synchro_mutex.remote.lock().await;
            let mut sync = Synchro::new(&mut local_fs, &mut remote_fs);
            sync.full_sync().await
        };

        match res {
            Ok(sync_res) => {
                // Propagate updates to the db
                for update in sync_res.local_updates() {
                    db.update_vfs(synchro_lock.read().await.local().id(), update)
                        .await?;
                }

                for update in sync_res.remote_updates() {
                    db.update_vfs(synchro_lock.read().await.remote().id(), update)
                        .await?;
                }

                let status = sync_res.status();
                let mut synchro = synchro_lock.write().await;
                debug!(
                    "Synchro {} returned with status: {status:?}",
                    synchro.name()
                );
                let status = status.into();
                synchro.set_status(status);
                db.set_synchro_status(id, status).await?;
                Ok(())
            }
            Err(err) => {
                let mut synchro = synchro_lock.write().await;
                error!("Synchro {} returned an error: {err}", synchro.name());
                let status = FullSyncStatus::from(&err).into();
                synchro.set_status(status);
                db.set_synchro_status(id, status).await?;
                Err(SynchroFailed {
                    synchro: synchro.to_owned(),
                    source: err,
                }
                .into())
            }
        }
    }

    /// Performs a [`full_sync`] on all the synchro in the list
    ///
    /// [`full_sync`]: brume::synchro::Synchro::full_sync
    pub async fn sync_all(&self, db: &Database) -> Vec<Result<(), SyncError>> {
        let futures: Vec<_> = self
            .synchros
            .iter()
            .map(|(id, synchro)| async move {
                if matches!(synchro.read().await.state(), SynchroState::Paused) {
                    return Ok(());
                }

                let (local_desc, remote_desc) = {
                    let sync = synchro.read().await;
                    (
                        sync.local().description().clone(),
                        sync.remote().description().clone(),
                    )
                };
                match (local_desc, remote_desc) {
                    (AnyFsDescription::LocalDir(_), AnyFsDescription::LocalDir(_)) => {
                        self.sync_one::<LocalDir, LocalDir>(*id, synchro, db).await
                    }
                    (AnyFsDescription::LocalDir(_), AnyFsDescription::Nextcloud(_)) => {
                        self.sync_one::<LocalDir, NextcloudFs>(*id, synchro, db)
                            .await
                    }
                    (AnyFsDescription::Nextcloud(_), AnyFsDescription::LocalDir(_)) => {
                        self.sync_one::<NextcloudFs, LocalDir>(*id, synchro, db)
                            .await
                    }
                    (AnyFsDescription::Nextcloud(_), AnyFsDescription::Nextcloud(_)) => {
                        self.sync_one::<NextcloudFs, NextcloudFs>(*id, synchro, db)
                            .await
                    }
                }
            })
            .collect();

        // TODO: switch to FutureUnordered ?
        join_all(futures).await
    }

    /// Sets the state of a synchro in the list
    pub async fn set_state(
        &self,
        id: SynchroId,
        state: SynchroState,
    ) -> Result<(), SynchroModificationError> {
        let sync = self
            .synchros
            .get(&id)
            .ok_or(SynchroModificationError::SynchroNotFound(id))?;

        sync.write().await.set_state(state);
        Ok(())
    }

    pub async fn get_vfs(&self, id: SynchroId, side: SynchroSide) -> Result<Vfs<()>, SyncError> {
        let synchro = self
            .synchros
            .get(&id)
            .ok_or_else(|| SyncError::SynchroNotFound(id))?
            .read()
            .await;

        let (desc, id) = match side {
            SynchroSide::Local => (synchro.local().description().clone(), synchro.local().id()),
            SynchroSide::Remote => (
                synchro.remote().description().clone(),
                synchro.remote().id(),
            ),
        };

        match desc {
            AnyFsDescription::LocalDir(_) => {
                let fs = self
                    .local_dir_list
                    .get(&id)
                    .ok_or_else(|| InvalidSynchro::from(synchro.clone()))?
                    .lock()
                    .await;

                Ok(fs.vfs().into())
            }
            AnyFsDescription::Nextcloud(_) => {
                let fs = self
                    .nextcloud_list
                    .get(&id)
                    .ok_or_else(|| InvalidSynchro::from(synchro.clone()))?
                    .lock()
                    .await;

                Ok(fs.vfs().into())
            }
        }
    }
}

/// A [`SynchroList`] that allows read-write access and can be shared between threads.
#[derive(Clone)]
pub struct ReadWriteSynchroList {
    maps: Arc<RwLock<SynchroList>>,
}

impl Default for ReadWriteSynchroList {
    fn default() -> Self {
        Self::new()
    }
}

impl From<SynchroList> for ReadWriteSynchroList {
    fn from(value: SynchroList) -> Self {
        Self {
            maps: Arc::new(RwLock::new(value)),
        }
    }
}

impl ReadWriteSynchroList {
    pub async fn read(&self) -> RwLockReadGuard<SynchroList> {
        self.maps.read().await
    }

    /// Inserts a new synchronized pair of filesystem in the list
    pub async fn insert(
        &self,
        sync_info: AnySynchroCreationInfo,
    ) -> Result<CreatedSynchro, SynchroCreationError> {
        self.maps.write().await.insert(sync_info).await
    }

    /// Deletes a synchronization from the list
    pub async fn remove(&self, id: SynchroId) -> Result<(), SynchroDeletionError> {
        self.maps.write().await.remove(id)
    }

    /// Forces a synchro of all the filesystems in the list, and updates the db accordingly
    pub async fn sync_all(&self, db: &Database) -> Vec<Result<(), SyncError>> {
        let maps = self.maps.read().await;

        maps.sync_all(db).await
    }

    /// Resolves a conflict on a path inside a synchro, by applying the update from `side`.
    /// Updates the db accordingly
    pub async fn resolve_conflict(
        &self,
        id: SynchroId,
        path: &VirtualPath,
        side: SynchroSide,
        db: &Database,
    ) -> Result<(), SyncError> {
        let maps = self.maps.read().await;

        maps.resolve_conflict(id, path, side, db).await
    }

    /// Returns a read-only view of the list
    pub fn as_read_only(&self) -> ReadOnlySynchroList {
        ReadOnlySynchroList {
            maps: self.maps.clone(),
        }
    }

    /// Creates a new empty list
    pub fn new() -> Self {
        Self {
            maps: Arc::new(RwLock::new(SynchroList::new())),
        }
    }

    pub async fn len(&self) -> usize {
        self.read().await.len()
    }

    pub async fn is_empty(&self) -> bool {
        self.len().await == 0
    }
}

#[cfg(test)]
mod test {
    use brume::concrete::{local::LocalDirCreationInfo, nextcloud::NextcloudFsCreationInfo};
    use brume_daemon_proto::{AnyFsCreationInfo, AnySynchroCreationInfo};

    use super::*;

    #[tokio::test]
    async fn test_insert_remove() {
        let mut list = SynchroList::new();

        let loc_a = LocalDirCreationInfo::new("/a");
        let loc_b = LocalDirCreationInfo::new("/b");
        let sync1 = AnySynchroCreationInfo::new(
            AnyFsCreationInfo::LocalDir(loc_a),
            AnyFsCreationInfo::LocalDir(loc_b),
            None,
        );

        let id1 = list.insert(sync1).await.unwrap().id();

        assert_eq!(list.synchros.len(), 1);
        assert_eq!(list.local_dir_list.len(), 2);
        assert_eq!(list.nextcloud_list.len(), 0);

        let nx_a = NextcloudFsCreationInfo::new("https://cloud.com", "user", "user");
        let loc_b = LocalDirCreationInfo::new("/b");
        let sync2 = AnySynchroCreationInfo::new(
            AnyFsCreationInfo::LocalDir(loc_b),
            AnyFsCreationInfo::Nextcloud(nx_a),
            None,
        );

        list.insert(sync2).await.unwrap();

        assert_eq!(list.synchros.len(), 2);
        assert_eq!(list.local_dir_list.len(), 3);
        assert_eq!(list.nextcloud_list.len(), 1);

        list.remove(id1).unwrap();

        assert_eq!(list.synchros.len(), 1);
        assert_eq!(list.local_dir_list.len(), 1);
        assert_eq!(list.nextcloud_list.len(), 1);
    }
}