cloud_sync_lib 0.1.0

Cloud storage provider synchronization library
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
//! Cloud storage provider implementations.
//!
//! This module houses individual provider clients (Google Drive, Dropbox, OneDrive)
//! and definitions for sharing OAuth client credentials.

use serde::{Deserialize, Serialize};
use zeroize::{Zeroize, ZeroizeOnDrop};

pub use cloud_sync_core::SyncMode;

/// Common configuration settings shared by all storage providers.
#[derive(Debug, Clone, Serialize, Deserialize, Default, Zeroize, ZeroizeOnDrop)]
pub struct CommonProviderSettings {
    /// Optional prefix folder in the remote storage where files will be synced.
    pub destination_folder: Option<String>,
    /// Optional toggle to enable/disable the provider backend.
    pub enabled: Option<bool>,
    /// Optional sync mode: two-way, one-way, one-way-no-deletions
    #[zeroize(skip)]
    pub sync_mode: Option<SyncMode>,
    /// Optional password for client-side encryption.
    pub encryption_password: Option<String>,
    /// Optional upload rate limit in KB/s.
    pub max_upload_rate: Option<u64>,
    /// Optional download rate limit in KB/s.
    pub max_download_rate: Option<u64>,
    /// Optional selective synchronization folder paths.
    #[zeroize(skip)]
    pub selective_sync: Option<Vec<String>>,
}

pub trait ProviderConfig {
    fn common_settings(&self) -> &CommonProviderSettings;

    fn is_enabled(&self) -> bool {
        self.common_settings().enabled.unwrap_or(true)
    }

    fn sync_mode(&self) -> SyncMode {
        self.common_settings().sync_mode.unwrap_or(SyncMode::OneWay)
    }

    fn sync_deletions(&self) -> bool {
        match self.sync_mode() {
            SyncMode::TwoWay | SyncMode::OneWay => true,
            SyncMode::OneWayNoDeletions => false,
        }
    }

    fn sync_both(&self) -> bool {
        match self.sync_mode() {
            SyncMode::TwoWay => true,
            SyncMode::OneWay | SyncMode::OneWayNoDeletions => false,
        }
    }

    fn destination_folder(&self) -> Option<&str> {
        self.common_settings().destination_folder.as_deref()
    }

    fn encryption_password(&self) -> Option<&str> {
        self.common_settings().encryption_password.as_deref()
    }

    fn max_upload_rate(&self) -> Option<u64> {
        self.common_settings().max_upload_rate
    }

    fn max_download_rate(&self) -> Option<u64> {
        self.common_settings().max_download_rate
    }

    fn selective_sync(&self) -> Option<Vec<String>> {
        self.common_settings().selective_sync.clone()
    }
}

/// Credentials configuration for OAuth2 authorization flows.
///
/// Contains client secrets and long-lived refresh tokens used to retrieve
/// short-lived access tokens dynamically during API execution.
#[derive(Debug, Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
pub struct OAuthCredentials {
    /// OAuth2 Client ID.
    pub client_id: String,
    /// OAuth2 Client Secret.
    pub client_secret: String,
    /// Long-lived Refresh Token.
    pub refresh_token: String,
    #[serde(flatten)]
    pub common: CommonProviderSettings,
}

impl ProviderConfig for OAuthCredentials {
    fn common_settings(&self) -> &CommonProviderSettings {
        &self.common
    }
}

/// Credentials and URL configuration for WebDAV servers.
#[derive(Debug, Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
pub struct WebDAVCredentials {
    /// WebDAV Server Base URL.
    pub url: String,
    /// WebDAV Username.
    pub username: String,
    /// WebDAV Password.
    pub password: String,
    #[serde(flatten)]
    pub common: CommonProviderSettings,
}

impl ProviderConfig for WebDAVCredentials {
    fn common_settings(&self) -> &CommonProviderSettings {
        &self.common
    }
}

/// Credentials configuration for Amazon S3 and S3-Compatible backends.
#[derive(Debug, Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
pub struct S3Credentials {
    /// S3 Bucket name.
    pub bucket: String,
    /// S3 Region name.
    pub region: String,
    /// S3 Access Key ID.
    pub access_key_id: String,
    /// S3 Secret Access Key.
    pub secret_access_key: String,
    /// Custom endpoint URL (optional, required for S3-compatible providers).
    pub endpoint: Option<String>,
    #[serde(flatten)]
    pub common: CommonProviderSettings,
}

impl ProviderConfig for S3Credentials {
    fn common_settings(&self) -> &CommonProviderSettings {
        &self.common
    }
}

/// Credentials configuration for SFTP.
#[derive(Debug, Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
pub struct SFTPCredentials {
    /// SFTP Host address.
    pub host: String,
    /// SFTP Port (defaults to 22 if None).
    pub port: Option<u16>,
    /// SFTP Username.
    pub username: String,
    /// SFTP Password (optional if using key-based auth).
    pub password: Option<String>,
    /// Path to the SSH private key (optional).
    pub private_key_path: Option<String>,
    #[serde(flatten)]
    pub common: CommonProviderSettings,
}

impl ProviderConfig for SFTPCredentials {
    fn common_settings(&self) -> &CommonProviderSettings {
        &self.common
    }
}

/// Credentials configuration for Nextcloud WebDAV and OCS services.
#[derive(Debug, Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
pub struct NextcloudCredentials {
    /// Nextcloud Server URL (e.g. https://nextcloud.example.com)
    pub url: String,
    /// Nextcloud Username.
    pub username: String,
    /// Nextcloud App Password.
    pub app_password: String,
    #[serde(flatten)]
    pub common: CommonProviderSettings,
}

impl ProviderConfig for NextcloudCredentials {
    fn common_settings(&self) -> &CommonProviderSettings {
        &self.common
    }
}

/// Credentials configuration for MEGA cloud storage.
#[derive(Debug, Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
pub struct MegaCredentials {
    /// MEGA Account Email.
    pub email: String,
    /// MEGA Account Password.
    pub password: String,
    #[serde(flatten)]
    pub common: CommonProviderSettings,
}

impl ProviderConfig for MegaCredentials {
    fn common_settings(&self) -> &CommonProviderSettings {
        &self.common
    }
}

/// Credentials configuration for Azure Blob Storage.
#[derive(Debug, Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
pub struct AzureBlobCredentials {
    /// Azure Storage Account name.
    pub account_name: String,
    /// Azure Storage Account Access Key.
    pub account_key: String,
    /// Target Container name.
    pub container: String,
    /// Custom endpoint URL (optional, used for local Azurite emulator).
    pub endpoint: Option<String>,
    #[serde(flatten)]
    pub common: CommonProviderSettings,
}

impl ProviderConfig for AzureBlobCredentials {
    fn common_settings(&self) -> &CommonProviderSettings {
        &self.common
    }
}

/// Credentials configuration for Google Cloud Storage (GCS).
#[derive(Debug, Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
pub struct GCSCredentials {
    /// Target Google Cloud Storage bucket name.
    pub bucket: String,
    /// Absolute path to the Service Account JSON credentials key file.
    pub service_account_key_path: String,
    /// Custom endpoint URL (optional, used for local fake-gcs-server emulator).
    pub endpoint: Option<String>,
    #[serde(flatten)]
    pub common: CommonProviderSettings,
}

impl ProviderConfig for GCSCredentials {
    fn common_settings(&self) -> &CommonProviderSettings {
        &self.common
    }
}

/// Credentials configuration for Backblaze B2.
#[derive(Debug, Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
pub struct B2Credentials {
    /// Target Backblaze B2 bucket name.
    pub bucket: String,
    /// Backblaze B2 Key ID.
    pub key_id: String,
    /// Backblaze B2 Application Key.
    pub application_key: String,
    /// Custom endpoint URL (optional, used for mocking / alternate endpoints).
    pub endpoint: Option<String>,
    #[serde(flatten)]
    pub common: CommonProviderSettings,
}

impl ProviderConfig for B2Credentials {
    fn common_settings(&self) -> &CommonProviderSettings {
        &self.common
    }
}

/// Credentials configuration for pCloud.
#[derive(Debug, Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
pub struct PCloudCredentials {
    /// pCloud OAuth2 Access Token.
    pub access_token: String,
    /// Custom API endpoint (optional, e.g. for European accounts or testing).
    pub endpoint: Option<String>,
    #[serde(flatten)]
    pub common: CommonProviderSettings,
}

impl ProviderConfig for PCloudCredentials {
    fn common_settings(&self) -> &CommonProviderSettings {
        &self.common
    }
}

/// Credentials configuration for IPFS Pinning Service (e.g. Pinata).
#[derive(Debug, Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
pub struct IPFSCredentials {
    /// JWT Bearer Token for authorization.
    pub jwt_token: String,
    /// Custom API endpoint (optional, defaults to Pinata's API https://api.pinata.cloud).
    pub endpoint: Option<String>,
    /// Gateway URL to resolve pinned CIDs (optional, defaults to https://gateway.pinata.cloud/ipfs/).
    pub gateway_url: Option<String>,
    #[serde(flatten)]
    pub common: CommonProviderSettings,
}

impl ProviderConfig for IPFSCredentials {
    fn common_settings(&self) -> &CommonProviderSettings {
        &self.common
    }
}

#[cfg(feature = "google_drive")]
pub mod google_drive;
#[cfg(feature = "dropbox")]
pub mod dropbox;
#[cfg(feature = "onedrive")]
pub mod onedrive;
#[cfg(feature = "webdav")]
pub mod webdav;
#[cfg(feature = "s3")]
pub mod s3;
#[cfg(feature = "sftp")]
pub mod sftp;
#[cfg(feature = "nextcloud")]
pub mod nextcloud;
#[cfg(feature = "box")]
pub mod box_provider;
#[cfg(feature = "mega")]
pub mod mega_provider;
#[cfg(feature = "azure_blob")]
pub mod azure_blob;
#[cfg(feature = "gcs")]
pub mod gcs;
#[cfg(feature = "b2")]
pub mod b2;
#[cfg(feature = "pcloud")]
pub mod pcloud;
#[cfg(feature = "ipfs")]
pub mod ipfs;
pub mod local_sim;
pub mod utils;
pub mod fallback;
pub mod encryption;


#[cfg(feature = "google_drive")]
pub use google_drive::{GoogleDriveProvider, GoogleDriveProviderBuilder};
#[cfg(feature = "dropbox")]
pub use dropbox::{DropboxProvider, DropboxProviderBuilder};
#[cfg(feature = "onedrive")]
pub use onedrive::{OneDriveProvider, OneDriveProviderBuilder};
#[cfg(feature = "webdav")]
pub use webdav::{WebDAVProvider, WebDAVProviderBuilder};
#[cfg(feature = "s3")]
pub use s3::{S3Provider, S3ProviderBuilder};
#[cfg(feature = "sftp")]
pub use sftp::{SFTPProvider, SFTPProviderBuilder};
#[cfg(feature = "nextcloud")]
pub use nextcloud::{NextcloudProvider, NextcloudProviderBuilder};
#[cfg(feature = "box")]
pub use box_provider::{BoxProvider, BoxProviderBuilder};
#[cfg(feature = "mega")]
pub use mega_provider::{MegaProvider, MegaProviderBuilder};
#[cfg(feature = "azure_blob")]
pub use azure_blob::{AzureBlobProvider, AzureBlobProviderBuilder};
#[cfg(feature = "gcs")]
pub use gcs::{GCSProvider, GCSProviderBuilder};
#[cfg(feature = "b2")]
pub use b2::{B2Provider, B2ProviderBuilder};
#[cfg(feature = "pcloud")]
pub use pcloud::{PCloudProvider, PCloudProviderBuilder};
#[cfg(feature = "ipfs")]
pub use ipfs::{IPFSProvider, IPFSProviderBuilder};
pub use fallback::SimulatedFallback;
pub use encryption::EncryptedBackend;
pub use utils::OAuthTokenManager;

use std::sync::Arc;
use crate::traits::StorageBackend;

/// Enum wrapping credentials for any compiled backend.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, zeroize::Zeroize)]
#[serde(tag = "type", content = "config")]
pub enum BackendCredentials {
    #[cfg(feature = "google_drive")]
    GoogleDrive(OAuthCredentials),
    #[cfg(feature = "dropbox")]
    Dropbox(OAuthCredentials),
    #[cfg(feature = "onedrive")]
    OneDrive(OAuthCredentials),
    #[cfg(feature = "webdav")]
    WebDAV(WebDAVCredentials),
    #[cfg(feature = "s3")]
    S3(S3Credentials),
    #[cfg(feature = "sftp")]
    SFTP(SFTPCredentials),
    #[cfg(feature = "nextcloud")]
    Nextcloud(NextcloudCredentials),
    #[cfg(feature = "box")]
    Box(OAuthCredentials),
    #[cfg(feature = "mega")]
    Mega(MegaCredentials),
    #[cfg(feature = "azure_blob")]
    AzureBlob(AzureBlobCredentials),
    #[cfg(feature = "gcs")]
    GCS(GCSCredentials),
    #[cfg(feature = "b2")]
    B2(B2Credentials),
    #[cfg(feature = "pcloud")]
    PCloud(PCloudCredentials),
    #[cfg(feature = "ipfs")]
    IPFS(IPFSCredentials),
}

#[allow(unreachable_patterns)]
impl ProviderConfig for BackendCredentials {
    fn common_settings(&self) -> &CommonProviderSettings {
        match self {
            #[cfg(feature = "google_drive")]
            BackendCredentials::GoogleDrive(c) => c.common_settings(),
            #[cfg(feature = "dropbox")]
            BackendCredentials::Dropbox(c) => c.common_settings(),
            #[cfg(feature = "onedrive")]
            BackendCredentials::OneDrive(c) => c.common_settings(),
            #[cfg(feature = "webdav")]
            BackendCredentials::WebDAV(c) => c.common_settings(),
            #[cfg(feature = "s3")]
            BackendCredentials::S3(c) => c.common_settings(),
            #[cfg(feature = "sftp")]
            BackendCredentials::SFTP(c) => c.common_settings(),
            #[cfg(feature = "nextcloud")]
            BackendCredentials::Nextcloud(c) => c.common_settings(),
            #[cfg(feature = "box")]
            BackendCredentials::Box(c) => c.common_settings(),
            #[cfg(feature = "mega")]
            BackendCredentials::Mega(c) => c.common_settings(),
            #[cfg(feature = "azure_blob")]
            BackendCredentials::AzureBlob(c) => c.common_settings(),
            #[cfg(feature = "gcs")]
            BackendCredentials::GCS(c) => c.common_settings(),
            #[cfg(feature = "b2")]
            BackendCredentials::B2(c) => c.common_settings(),
            #[cfg(feature = "pcloud")]
            BackendCredentials::PCloud(c) => c.common_settings(),
            #[cfg(feature = "ipfs")]
            BackendCredentials::IPFS(c) => c.common_settings(),
            _ => unreachable!(),
        }
    }
}

impl BackendCredentials {
    pub fn sync_mode(&self) -> SyncMode {
        ProviderConfig::sync_mode(self)
    }

    pub fn selective_sync(&self) -> Option<Vec<String>> {
        ProviderConfig::selective_sync(self)
    }
}

/// Unified factory registry to build storage providers dynamically.
pub struct BackendRegistry;

impl BackendRegistry {
    /// Dynamically instantiates a provider using its config credentials.
    pub fn build(mut creds: BackendCredentials) -> Arc<dyn StorageBackend> {
        match &mut creds {
            #[cfg(feature = "google_drive")]
            BackendCredentials::GoogleDrive(ref mut c) => {
                c.client_secret = utils::get_secure_credential("google_drive", "client_secret", &c.client_secret);
                c.refresh_token = utils::get_secure_credential("google_drive", "refresh_token", &c.refresh_token);
            }
            #[cfg(feature = "dropbox")]
            BackendCredentials::Dropbox(ref mut c) => {
                c.client_secret = utils::get_secure_credential("dropbox", "client_secret", &c.client_secret);
                c.refresh_token = utils::get_secure_credential("dropbox", "refresh_token", &c.refresh_token);
            }
            #[cfg(feature = "onedrive")]
            BackendCredentials::OneDrive(ref mut c) => {
                c.client_secret = utils::get_secure_credential("onedrive", "client_secret", &c.client_secret);
                c.refresh_token = utils::get_secure_credential("onedrive", "refresh_token", &c.refresh_token);
            }
            #[cfg(feature = "webdav")]
            BackendCredentials::WebDAV(ref mut c) => {
                c.password = utils::get_secure_credential("webdav", "password", &c.password);
            }
            #[cfg(feature = "s3")]
            BackendCredentials::S3(ref mut c) => {
                c.secret_access_key = utils::get_secure_credential("s3", "secret_access_key", &c.secret_access_key);
            }
            #[cfg(feature = "sftp")]
            BackendCredentials::SFTP(ref mut c) => {
                if let Some(ref mut pwd) = c.password {
                    *pwd = utils::get_secure_credential("sftp", "password", pwd);
                }
            }
            #[cfg(feature = "nextcloud")]
            BackendCredentials::Nextcloud(ref mut c) => {
                c.app_password = utils::get_secure_credential("nextcloud", "app_password", &c.app_password);
            }
            #[cfg(feature = "box")]
            BackendCredentials::Box(ref mut c) => {
                c.client_secret = utils::get_secure_credential("box", "client_secret", &c.client_secret);
                c.refresh_token = utils::get_secure_credential("box", "refresh_token", &c.refresh_token);
            }
            #[cfg(feature = "mega")]
            BackendCredentials::Mega(ref mut c) => {
                c.password = utils::get_secure_credential("mega", "password", &c.password);
            }
            #[cfg(feature = "azure_blob")]
            BackendCredentials::AzureBlob(ref mut c) => {
                c.account_key = utils::get_secure_credential("azure_blob", "account_key", &c.account_key);
            }
            #[cfg(feature = "b2")]
            BackendCredentials::B2(ref mut c) => {
                c.application_key = utils::get_secure_credential("b2", "application_key", &c.application_key);
            }
            #[cfg(feature = "pcloud")]
            BackendCredentials::PCloud(ref mut c) => {
                c.access_token = utils::get_secure_credential("pcloud", "access_token", &c.access_token);
            }
            #[cfg(feature = "ipfs")]
            BackendCredentials::IPFS(ref mut c) => {
                c.jwt_token = utils::get_secure_credential("ipfs", "jwt_token", &c.jwt_token);
            }
            _ => {}
        }

        match creds {
            #[cfg(feature = "google_drive")]
            BackendCredentials::GoogleDrive(c) => Arc::new(GoogleDriveProvider::new(c)),
            #[cfg(feature = "dropbox")]
            BackendCredentials::Dropbox(c) => Arc::new(DropboxProvider::new(c)),
            #[cfg(feature = "onedrive")]
            BackendCredentials::OneDrive(c) => Arc::new(OneDriveProvider::new(c)),
            #[cfg(feature = "webdav")]
            BackendCredentials::WebDAV(c) => Arc::new(WebDAVProvider::new(c)),
            #[cfg(feature = "s3")]
            BackendCredentials::S3(c) => Arc::new(S3Provider::new(c)),
            #[cfg(feature = "sftp")]
            BackendCredentials::SFTP(c) => Arc::new(SFTPProvider::new(c)),
            #[cfg(feature = "nextcloud")]
            BackendCredentials::Nextcloud(c) => Arc::new(NextcloudProvider::new(c)),
            #[cfg(feature = "box")]
            BackendCredentials::Box(c) => Arc::new(BoxProvider::new(c)),
            #[cfg(feature = "mega")]
            BackendCredentials::Mega(c) => Arc::new(MegaProvider::new(c)),
            #[cfg(feature = "azure_blob")]
            BackendCredentials::AzureBlob(c) => Arc::new(AzureBlobProvider::new(c)),
            #[cfg(feature = "gcs")]
            BackendCredentials::GCS(c) => Arc::new(GCSProvider::new(c)),
            #[cfg(feature = "b2")]
            BackendCredentials::B2(c) => Arc::new(B2Provider::new(c)),
            #[cfg(feature = "pcloud")]
            BackendCredentials::PCloud(c) => Arc::new(PCloudProvider::new(c)),
            #[cfg(feature = "ipfs")]
            BackendCredentials::IPFS(c) => Arc::new(IPFSProvider::new(c)),
        }
    }

    /// Dynamically instantiates a fully wrapped provider (with fallback/encryption/limiters) using its config credentials.
    #[allow(unreachable_patterns, unreachable_code, unused_variables)]
    pub fn build_wrapped(
        creds: BackendCredentials,
        sim_root: std::path::PathBuf,
        global_upload_limiter: Option<crate::rate_limit::TokenBucket>,
        global_download_limiter: Option<crate::rate_limit::TokenBucket>,
    ) -> Arc<dyn StorageBackend> {
        let provider_name: &str = match &creds {
            #[cfg(feature = "google_drive")]
            BackendCredentials::GoogleDrive(_) => "Google Drive",
            #[cfg(feature = "dropbox")]
            BackendCredentials::Dropbox(_) => "Dropbox",
            #[cfg(feature = "onedrive")]
            BackendCredentials::OneDrive(_) => "OneDrive",
            #[cfg(feature = "webdav")]
            BackendCredentials::WebDAV(_) => "WebDAV",
            #[cfg(feature = "s3")]
            BackendCredentials::S3(_) => "S3",
            #[cfg(feature = "sftp")]
            BackendCredentials::SFTP(_) => "SFTP",
            #[cfg(feature = "nextcloud")]
            BackendCredentials::Nextcloud(_) => "Nextcloud",
            #[cfg(feature = "box")]
            BackendCredentials::Box(_) => "Box",
            #[cfg(feature = "mega")]
            BackendCredentials::Mega(_) => "MEGA",
            #[cfg(feature = "azure_blob")]
            BackendCredentials::AzureBlob(_) => "Azure Blob",
            #[cfg(feature = "gcs")]
            BackendCredentials::GCS(_) => "GCS",
            #[cfg(feature = "b2")]
            BackendCredentials::B2(_) => "B2",
            #[cfg(feature = "pcloud")]
            BackendCredentials::PCloud(_) => "pCloud",
            #[cfg(feature = "ipfs")]
            BackendCredentials::IPFS(_) => "IPFS",
            _ => unreachable!(),
        };

        let sync_mode = creds.sync_mode();
        let max_upload_rate = creds.max_upload_rate();
        let max_download_rate = creds.max_download_rate();
        let encryption_password = creds.encryption_password();

        let upload_limiter = max_upload_rate
            .map(|rate| crate::rate_limit::TokenBucket::new(rate * 1024))
            .or(global_upload_limiter);
        let download_limiter = max_download_rate
            .map(|rate| crate::rate_limit::TokenBucket::new(rate * 1024))
            .or(global_download_limiter);

        let inner = Self::build(creds.clone());

        let local_sim = local_sim::LocalSimulation::new(sim_root, provider_name.to_string())
            .with_limiters(upload_limiter.clone(), download_limiter.clone());
        let fallback = fallback::SimulatedFallback::new(Some(inner), local_sim, provider_name, sync_mode);

        let rate_limited = crate::rate_limit::RateLimitingBackend::new(
            fallback,
            upload_limiter,
            download_limiter,
        );

        if let Some(password) = encryption_password {
            Arc::new(encryption::EncryptedBackend::new(rate_limited, password))
        } else {
            Arc::new(rate_limited)
        }
    }

    /// Convenience factory to build a fully wrapped storage backend with default limiters.
    pub fn create_backend(
        creds: BackendCredentials,
        sim_root: std::path::PathBuf,
    ) -> Arc<dyn StorageBackend> {
        Self::build_wrapped(creds, sim_root, None, None)
    }
}