pipedash-core 0.9.0

Framework-agnostic core library for Pipedash
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
use std::collections::HashMap;
use std::sync::Arc;

use chrono::{
    DateTime,
    Utc,
};
use serde::{
    Deserialize,
    Serialize,
};
use tokio::sync::RwLock;
use tracing::{
    debug,
    info,
};

use crate::domain::{
    DomainError,
    DomainResult,
};
use crate::infrastructure::storage::{
    ObjectMetadata,
    StorageBackend,
};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SyncDirection {
    Push,
    Pull,
    Bidirectional,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ConflictResolution {
    #[default]
    LastWriteWins,
    PreferLocal,
    PreferRemote,
    Skip,
}

#[derive(Debug, Clone)]
pub struct SyncConfig {
    pub direction: SyncDirection,
    pub conflict_resolution: ConflictResolution,
    pub include_prefixes: Vec<String>,
    pub exclude_prefixes: Vec<String>,
    pub delete_orphaned: bool,
    pub dry_run: bool,
}

impl Default for SyncConfig {
    fn default() -> Self {
        Self {
            direction: SyncDirection::Bidirectional,
            conflict_resolution: ConflictResolution::LastWriteWins,
            include_prefixes: vec![],
            exclude_prefixes: vec![
                "pipedash.db".to_string(),
                "metrics.db".to_string(),
                "cache/".to_string(),
            ],
            delete_orphaned: false,
            dry_run: false,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncFileResult {
    pub key: String,
    pub action: SyncAction,
    pub success: bool,
    pub error: Option<String>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum SyncAction {
    Pushed,
    Pulled,
    Skipped,
    DeletedRemote,
    DeletedLocal,
    NoChange,
    Conflict,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SyncResult {
    pub pushed: usize,
    pub pulled: usize,
    pub skipped: usize,
    pub conflicts: usize,
    pub deleted: usize,
    pub errors: usize,
    pub files: Vec<SyncFileResult>,
    pub started_at: DateTime<Utc>,
    pub completed_at: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SyncState {
    pub last_sync: Option<DateTime<Utc>>,
    pub file_checksums: HashMap<String, String>,
    pub file_timestamps: HashMap<String, DateTime<Utc>>,
}

pub struct SyncManager {
    local: Arc<dyn StorageBackend>,
    remote: Option<Arc<dyn StorageBackend>>,
    state: RwLock<SyncState>,
    default_config: SyncConfig,
}

impl SyncManager {
    pub fn new(local: Arc<dyn StorageBackend>) -> Self {
        Self {
            local,
            remote: None,
            state: RwLock::new(SyncState::default()),
            default_config: SyncConfig::default(),
        }
    }

    pub fn with_remote(local: Arc<dyn StorageBackend>, remote: Arc<dyn StorageBackend>) -> Self {
        Self {
            local,
            remote: Some(remote),
            state: RwLock::new(SyncState::default()),
            default_config: SyncConfig::default(),
        }
    }

    pub fn set_remote(&mut self, remote: Arc<dyn StorageBackend>) {
        self.remote = Some(remote);
    }

    pub fn clear_remote(&mut self) {
        self.remote = None;
    }

    pub fn has_remote(&self) -> bool {
        self.remote.is_some()
    }

    pub fn remote_type(&self) -> Option<&str> {
        self.remote.as_ref().map(|r| r.backend_type())
    }

    pub fn set_default_config(&mut self, config: SyncConfig) {
        self.default_config = config;
    }

    fn should_sync_key(&self, key: &str, config: &SyncConfig) -> bool {
        for prefix in &config.exclude_prefixes {
            if key.starts_with(prefix) {
                return false;
            }
        }

        if config.include_prefixes.is_empty() {
            return true;
        }

        for prefix in &config.include_prefixes {
            if key.starts_with(prefix) {
                return true;
            }
        }

        false
    }

    fn determine_action(
        &self, _key: &str, local_meta: Option<&ObjectMetadata>,
        remote_meta: Option<&ObjectMetadata>, config: &SyncConfig,
    ) -> SyncAction {
        match (local_meta, remote_meta) {
            (None, None) => SyncAction::NoChange,
            (Some(_), None) => match config.direction {
                SyncDirection::Push | SyncDirection::Bidirectional => SyncAction::Pushed,
                SyncDirection::Pull => {
                    if config.delete_orphaned {
                        SyncAction::DeletedLocal
                    } else {
                        SyncAction::Skipped
                    }
                }
            },
            (None, Some(_)) => match config.direction {
                SyncDirection::Pull | SyncDirection::Bidirectional => SyncAction::Pulled,
                SyncDirection::Push => {
                    if config.delete_orphaned {
                        SyncAction::DeletedRemote
                    } else {
                        SyncAction::Skipped
                    }
                }
            },
            (Some(local), Some(remote)) => {
                let local_id = local.etag.as_ref().unwrap_or(&"".to_string()).clone();
                let remote_id = remote.etag.as_ref().unwrap_or(&"".to_string()).clone();

                if !local_id.is_empty() && !remote_id.is_empty() && local_id == remote_id {
                    return SyncAction::NoChange;
                }

                match config.conflict_resolution {
                    ConflictResolution::LastWriteWins => {
                        if local.last_modified > remote.last_modified {
                            SyncAction::Pushed
                        } else if remote.last_modified > local.last_modified {
                            SyncAction::Pulled
                        } else {
                            SyncAction::NoChange
                        }
                    }
                    ConflictResolution::PreferLocal => SyncAction::Pushed,
                    ConflictResolution::PreferRemote => SyncAction::Pulled,
                    ConflictResolution::Skip => SyncAction::Conflict,
                }
            }
        }
    }

    pub async fn sync(&self, config: Option<SyncConfig>) -> DomainResult<SyncResult> {
        let config = config.unwrap_or_else(|| self.default_config.clone());
        let mut result = SyncResult {
            started_at: Utc::now(),
            ..Default::default()
        };

        let remote = match &self.remote {
            Some(r) => r,
            None => {
                info!("No remote storage configured, skipping sync");
                result.completed_at = Some(Utc::now());
                return Ok(result);
            }
        };

        if !remote.is_available().await {
            return Err(DomainError::NetworkError(
                "Remote storage is not available".to_string(),
            ));
        }

        info!(
            "Starting sync: direction={:?}, conflict_resolution={:?}",
            config.direction, config.conflict_resolution
        );

        let local_files = self.local.list(None).await?;
        let remote_files = remote.list(None).await?;

        let local_map: HashMap<String, ObjectMetadata> = local_files
            .into_iter()
            .filter(|f| self.should_sync_key(&f.key, &config))
            .map(|f| (f.key.clone(), f))
            .collect();

        let remote_map: HashMap<String, ObjectMetadata> = remote_files
            .into_iter()
            .filter(|f| self.should_sync_key(&f.key, &config))
            .map(|f| (f.key.clone(), f))
            .collect();

        let mut all_keys: Vec<String> = local_map.keys().cloned().collect();
        for key in remote_map.keys() {
            if !all_keys.contains(key) {
                all_keys.push(key.clone());
            }
        }

        for key in all_keys {
            let local_meta = local_map.get(&key);
            let remote_meta = remote_map.get(&key);
            let action = self.determine_action(&key, local_meta, remote_meta, &config);

            debug!("Processing {}: action={:?}", key, action);

            if config.dry_run {
                result.files.push(SyncFileResult {
                    key: key.clone(),
                    action,
                    success: true,
                    error: None,
                });
                match action {
                    SyncAction::Pushed => result.pushed += 1,
                    SyncAction::Pulled => result.pulled += 1,
                    SyncAction::Skipped | SyncAction::NoChange => result.skipped += 1,
                    SyncAction::Conflict => result.conflicts += 1,
                    SyncAction::DeletedLocal | SyncAction::DeletedRemote => result.deleted += 1,
                }
                continue;
            }

            let file_result = match action {
                SyncAction::Pushed => self.push_file(&key, remote.as_ref()).await,
                SyncAction::Pulled => self.pull_file(&key, remote.as_ref()).await,
                SyncAction::DeletedRemote => self.delete_remote(&key, remote.as_ref()).await,
                SyncAction::DeletedLocal => self.delete_local(&key).await,
                SyncAction::NoChange | SyncAction::Skipped | SyncAction::Conflict => {
                    Ok(SyncFileResult {
                        key: key.clone(),
                        action,
                        success: true,
                        error: None,
                    })
                }
            };

            match file_result {
                Ok(file_res) => {
                    match file_res.action {
                        SyncAction::Pushed => result.pushed += 1,
                        SyncAction::Pulled => result.pulled += 1,
                        SyncAction::Skipped | SyncAction::NoChange => result.skipped += 1,
                        SyncAction::Conflict => result.conflicts += 1,
                        SyncAction::DeletedLocal | SyncAction::DeletedRemote => result.deleted += 1,
                    }
                    result.files.push(file_res);
                }
                Err(e) => {
                    result.errors += 1;
                    result.files.push(SyncFileResult {
                        key: key.clone(),
                        action,
                        success: false,
                        error: Some(e.to_string()),
                    });
                }
            }
        }

        {
            let mut state = self.state.write().await;
            state.last_sync = Some(Utc::now());
        }

        result.completed_at = Some(Utc::now());
        info!(
            "Sync completed: pushed={}, pulled={}, skipped={}, conflicts={}, errors={}",
            result.pushed, result.pulled, result.skipped, result.conflicts, result.errors
        );

        Ok(result)
    }

    async fn push_file(
        &self, key: &str, remote: &dyn StorageBackend,
    ) -> DomainResult<SyncFileResult> {
        debug!("Pushing file: {}", key);
        let data = self.local.get(key).await?;
        remote.put(key, &data, None).await?;

        Ok(SyncFileResult {
            key: key.to_string(),
            action: SyncAction::Pushed,
            success: true,
            error: None,
        })
    }

    async fn pull_file(
        &self, key: &str, remote: &dyn StorageBackend,
    ) -> DomainResult<SyncFileResult> {
        debug!("Pulling file: {}", key);
        let data = remote.get(key).await?;
        self.local.put(key, &data, None).await?;

        Ok(SyncFileResult {
            key: key.to_string(),
            action: SyncAction::Pulled,
            success: true,
            error: None,
        })
    }

    async fn delete_remote(
        &self, key: &str, remote: &dyn StorageBackend,
    ) -> DomainResult<SyncFileResult> {
        debug!("Deleting remote file: {}", key);
        remote.delete(key).await?;

        Ok(SyncFileResult {
            key: key.to_string(),
            action: SyncAction::DeletedRemote,
            success: true,
            error: None,
        })
    }

    async fn delete_local(&self, key: &str) -> DomainResult<SyncFileResult> {
        debug!("Deleting local file: {}", key);
        self.local.delete(key).await?;

        Ok(SyncFileResult {
            key: key.to_string(),
            action: SyncAction::DeletedLocal,
            success: true,
            error: None,
        })
    }

    pub async fn force_push(&self) -> DomainResult<SyncResult> {
        self.sync(Some(SyncConfig {
            direction: SyncDirection::Push,
            conflict_resolution: ConflictResolution::PreferLocal,
            delete_orphaned: true,
            ..self.default_config.clone()
        }))
        .await
    }

    pub async fn force_pull(&self) -> DomainResult<SyncResult> {
        self.sync(Some(SyncConfig {
            direction: SyncDirection::Pull,
            conflict_resolution: ConflictResolution::PreferRemote,
            delete_orphaned: true,
            ..self.default_config.clone()
        }))
        .await
    }

    pub async fn preview(&self, config: Option<SyncConfig>) -> DomainResult<SyncResult> {
        let mut config = config.unwrap_or_else(|| self.default_config.clone());
        config.dry_run = true;
        self.sync(Some(config)).await
    }

    pub async fn last_sync_time(&self) -> Option<DateTime<Utc>> {
        self.state.read().await.last_sync
    }

    pub async fn get_state(&self) -> SyncState {
        self.state.read().await.clone()
    }
}

#[cfg(test)]
mod tests {
    use tempfile::TempDir;

    use super::*;
    use crate::infrastructure::storage::LocalStorage;

    #[tokio::test]
    async fn test_sync_manager_creation() {
        let temp_dir = TempDir::new().unwrap();
        let storage = Arc::new(LocalStorage::new(temp_dir.path().to_path_buf()));
        let manager = SyncManager::new(storage);

        assert!(!manager.has_remote());
        assert!(manager.remote_type().is_none());
    }

    #[tokio::test]
    async fn test_sync_without_remote() {
        let temp_dir = TempDir::new().unwrap();
        let storage = Arc::new(LocalStorage::new(temp_dir.path().to_path_buf()));
        let manager = SyncManager::new(storage);

        let result = manager.sync(None).await.unwrap();
        assert_eq!(result.pushed, 0);
        assert_eq!(result.pulled, 0);
        assert_eq!(result.errors, 0);
    }

    #[tokio::test]
    async fn test_should_sync_key() {
        let temp_dir = TempDir::new().unwrap();
        let storage = Arc::new(LocalStorage::new(temp_dir.path().to_path_buf()));
        let manager = SyncManager::new(storage);

        let config = SyncConfig {
            exclude_prefixes: vec!["cache/".to_string(), ".git/".to_string()],
            include_prefixes: vec![],
            ..Default::default()
        };

        assert!(manager.should_sync_key("config/settings.json", &config));
        assert!(!manager.should_sync_key("cache/temp.bin", &config));
        assert!(!manager.should_sync_key(".git/config", &config));
    }

    #[tokio::test]
    async fn test_sync_between_local_storages() {
        let local_dir = TempDir::new().unwrap();
        let remote_dir = TempDir::new().unwrap();

        let local = Arc::new(LocalStorage::new(local_dir.path().to_path_buf()));
        let remote: Arc<dyn StorageBackend> =
            Arc::new(LocalStorage::new(remote_dir.path().to_path_buf()));

        local.put("test.txt", b"hello world", None).await.unwrap();

        let manager = SyncManager::with_remote(local.clone(), remote.clone());

        let result = manager
            .sync(Some(SyncConfig {
                direction: SyncDirection::Push,
                ..Default::default()
            }))
            .await
            .unwrap();

        assert_eq!(result.pushed, 1);
        assert_eq!(result.errors, 0);

        let remote_data = remote.get("test.txt").await.unwrap();
        assert_eq!(remote_data, b"hello world");
    }
}