vdsl-sync 0.2.0

File synchronization engine — N-location, pluggable store & backend
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
//! TransferRoute — directed transfer route between two locations.
//!
//! Lives in the application layer because it holds infrastructure types
//! ([`StorageBackend`], [`RemoteShell`]). The domain layer only knows
//! about the topology via [`Topology`](crate::domain::plan::Topology).
//!
//! Encapsulates "how to move a file from src to dest", including
//! path resolution for both ends and backend delegation.

use std::path::{Path, PathBuf};

use std::collections::HashMap;

use crate::application::error::SyncError;
use crate::domain::location::LocationId;
use crate::infra::backend::StorageBackend;
use crate::infra::error::InfraError;
use crate::infra::shell::RemoteShell;

/// Direction of file transfer relative to the rclone remote.
///
/// - `Push`: src is a "local" filesystem path, dest is a rclone remote path.
///   `backend.push(src_path, dest_path)` → `rclone copyto <local> <remote>`
///
/// - `Pull`: src is a rclone remote path, dest is a "local" filesystem path.
///   `backend.pull(src_path, dest_path)` → `rclone copyto <remote> <local>`
///
/// "Local" here means local to the host running rclone — which may be a Pod
/// if the backend uses a `RemoteShell`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TransferDirection {
    #[default]
    Push,
    Pull,
}

/// A directed transfer route between two locations.
///
/// # Path model
///
/// - `src_file_root`: base directory on the src location's host.
///   For local: `/Users/.../output`. For pod: `/workspace/comfyui/output`.
/// - `dest_file_root`: base directory on the dest location's host.
///   For cloud: `"vdsl/output"`. For local: `/Users/.../output`.
///
/// Full paths:
/// - src:  `src_file_root / relative_path`
/// - dest: `dest_file_root / relative_path`
///
/// # Source shell
///
/// `src_shell` enables operations on the source host: file existence checks,
/// hash computation, etc. For local sources this is `None` (use filesystem).
/// For remote sources (pod, NAS), provide a `RemoteShell` implementation.
///
/// # Backend responsibility
///
/// `backend.push(src_full_path, dest_full_path)` is called.
/// The Backend internally uses a `RemoteShell` to determine
/// WHERE the command (e.g. rclone) runs.
pub struct TransferRoute {
    src: LocationId,
    dest: LocationId,
    src_file_root: PathBuf,
    dest_file_root: PathBuf,
    backend: Box<dyn StorageBackend>,
    /// Shell for source-side file operations (existence check, hash).
    /// `None` when src is local (use filesystem directly).
    src_shell: Option<Box<dyn RemoteShell>>,
    direction: TransferDirection,
    /// Estimated transfer time per GB for this route.
    /// Used by the topology resolver to prefer cheaper routes.
    /// Default: 1.0 (neutral).
    time_per_gb: f64,
    /// Static priority (lower = preferred when costs are equal).
    /// Default: 100 (neutral).
    priority: u32,
}

impl TransferRoute {
    /// Create a push-direction route (default).
    ///
    /// Chain `.direction()` and `.with_src_shell()` for pull-direction or
    /// remote-source routes:
    ///
    /// ```ignore
    /// // Push, local source (default)
    /// TransferRoute::new(src, dest, src_root, dest_root, backend)
    ///
    /// // Pull direction
    /// TransferRoute::new(src, dest, src_root, dest_root, backend)
    ///     .direction(TransferDirection::Pull)
    ///
    /// // Remote source with shell
    /// TransferRoute::new(src, dest, src_root, dest_root, backend)
    ///     .with_src_shell(shell)
    ///
    /// // Pull + remote source
    /// TransferRoute::new(src, dest, src_root, dest_root, backend)
    ///     .direction(TransferDirection::Pull)
    ///     .with_src_shell(shell)
    /// ```
    pub fn new(
        src: LocationId,
        dest: LocationId,
        src_file_root: PathBuf,
        dest_file_root: PathBuf,
        backend: Box<dyn StorageBackend>,
    ) -> Self {
        Self {
            src,
            dest,
            src_file_root,
            dest_file_root,
            backend,
            src_shell: None,
            direction: TransferDirection::Push,
            time_per_gb: 1.0,
            priority: 100,
        }
    }

    /// Set the transfer direction (default: Push).
    ///
    /// Pull direction: `backend.pull()` is called instead of `push()`.
    /// Use for cloud→local or cloud→pod routes where the rclone remote
    /// is the source.
    pub fn direction(mut self, direction: TransferDirection) -> Self {
        self.direction = direction;
        self
    }

    /// Set the source shell for remote source operations.
    ///
    /// Enables file existence checks and hash computation on the source
    /// host (e.g., a GPU pod via SSH). Without a shell, the source is
    /// assumed to be locally accessible.
    pub fn with_src_shell(mut self, shell: Box<dyn RemoteShell>) -> Self {
        self.src_shell = Some(shell);
        self
    }

    /// Set the transfer cost properties for this route.
    ///
    /// `time_per_gb`: estimated seconds per GB (lower = cheaper, preferred).
    /// `priority`: static tiebreaker (lower = preferred when costs are equal).
    ///
    /// Used internally by the topology resolver to compute optimal transfer
    /// trees. Routes with higher cost are used only when cheaper paths are
    /// unavailable.
    pub fn with_cost(mut self, time_per_gb: f64, priority: u32) -> Self {
        self.time_per_gb = time_per_gb;
        self.priority = priority;
        self
    }

    /// Estimated transfer time per GB.
    pub fn time_per_gb(&self) -> f64 {
        self.time_per_gb
    }

    /// Static priority (lower = preferred).
    pub fn priority(&self) -> u32 {
        self.priority
    }

    pub fn src(&self) -> &LocationId {
        &self.src
    }

    pub fn dest(&self) -> &LocationId {
        &self.dest
    }

    pub fn src_file_root(&self) -> &Path {
        &self.src_file_root
    }

    /// Whether this route is a pull-direction transfer.
    ///
    /// Pull routes have a remote (e.g. rclone) source that cannot be checked
    /// via local filesystem. Source file existence is guaranteed by the
    /// preceding push transfer's Completed state.
    pub fn is_pull(&self) -> bool {
        self.direction == TransferDirection::Pull
    }

    /// Access the underlying storage backend.
    pub(crate) fn backend(&self) -> &dyn StorageBackend {
        &*self.backend
    }

    /// Transfer a file along this route.
    ///
    /// Resolves both src and dest full paths from the relative path,
    /// validates against path traversal, then delegates to the backend.
    ///
    /// - Push direction: `backend.push(src_local_path, dest_remote_str)`
    /// - Pull direction: `backend.pull(src_remote_str, dest_local_path)`
    pub async fn transfer(&self, relative_path: &str) -> Result<(), SyncError> {
        Self::validate_relative_path(relative_path)?;

        let src_path = self.src_file_root.join(relative_path);
        let dest_path = Self::safe_join(&self.dest_file_root, relative_path);

        match self.direction {
            TransferDirection::Push => {
                let dest_str = dest_path.to_str().ok_or_else(|| -> SyncError {
                    InfraError::Transfer {
                        reason: format!(
                            "dest path is not valid UTF-8: {}",
                            dest_path.to_string_lossy()
                        ),
                    }
                    .into()
                })?;
                self.backend
                    .push(&src_path, dest_str)
                    .await
                    .map_err(Into::into)
            }
            TransferDirection::Pull => {
                let src_str = src_path.to_str().ok_or_else(|| -> SyncError {
                    InfraError::Transfer {
                        reason: format!(
                            "src path is not valid UTF-8: {}",
                            src_path.to_string_lossy()
                        ),
                    }
                    .into()
                })?;
                self.backend
                    .pull(src_str, &dest_path)
                    .await
                    .map_err(Into::into)
            }
        }
    }

    /// Delete a file at the destination of this route.
    ///
    /// For push-direction routes, deletes from the remote (dest_file_root).
    /// For pull-direction routes, deletes from the local dest.
    pub async fn delete(&self, relative_path: &str) -> Result<(), SyncError> {
        Self::validate_relative_path(relative_path)?;
        let dest_path = Self::safe_join(&self.dest_file_root, relative_path);

        match self.direction {
            TransferDirection::Push => {
                // dest is remote — use backend.delete
                let dest_str = dest_path.to_str().ok_or_else(|| -> SyncError {
                    InfraError::Transfer {
                        reason: format!(
                            "dest path is not valid UTF-8: {}",
                            dest_path.to_string_lossy()
                        ),
                    }
                    .into()
                })?;
                self.backend.delete(dest_str).await.map_err(Into::into)
            }
            TransferDirection::Pull => {
                // dest is local — remove from filesystem
                match tokio::fs::remove_file(&dest_path).await {
                    Ok(()) => Ok(()),
                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
                    Err(e) => Err(SyncError::from(e)),
                }
            }
        }
    }

    /// Batch transfer multiple files along this route in a single operation.
    ///
    /// Uses `backend.push_batch()` with `--files-from` for rclone backends.
    /// For sync transfers only. Delete transfers use `delete_batch()`.
    ///
    /// Returns per-file Ok/Err results keyed by relative path.
    pub async fn transfer_batch(
        &self,
        relative_paths: &[String],
    ) -> HashMap<String, Result<(), SyncError>> {
        if relative_paths.is_empty() {
            return HashMap::new();
        }

        // Validate all paths first
        for rel in relative_paths {
            if Self::validate_relative_path(rel).is_err() {
                return relative_paths
                    .iter()
                    .map(|p| {
                        (
                            p.clone(),
                            Err(SyncError::OutsideSyncRoot { path: p.clone() }),
                        )
                    })
                    .collect();
            }
        }

        match self.direction {
            TransferDirection::Push => {
                let dest_root_str = self.dest_file_root.to_str().unwrap_or_default();
                self.backend
                    .push_batch(&self.src_file_root, dest_root_str, relative_paths)
                    .await
                    .into_iter()
                    .map(|(k, v)| (k, v.map_err(Into::into)))
                    .collect()
            }
            TransferDirection::Pull => {
                let src_root_str = self.src_file_root.to_str().unwrap_or_default();
                self.backend
                    .pull_batch(src_root_str, &self.dest_file_root, relative_paths)
                    .await
                    .into_iter()
                    .map(|(k, v)| (k, v.map_err(Into::into)))
                    .collect()
            }
        }
    }

    /// Batch delete multiple files along this route in a single operation.
    ///
    /// Uses `backend.delete_batch()` with `rclone delete --files-from`.
    /// For push-direction routes, deletes from dest (remote).
    /// For pull-direction routes, deletes from dest (local) — falls back to individual.
    ///
    /// Returns per-file Ok/Err results keyed by relative path.
    pub async fn delete_batch(
        &self,
        relative_paths: &[String],
    ) -> HashMap<String, Result<(), SyncError>> {
        if relative_paths.is_empty() {
            return HashMap::new();
        }

        for rel in relative_paths {
            if Self::validate_relative_path(rel).is_err() {
                return relative_paths
                    .iter()
                    .map(|p| {
                        (
                            p.clone(),
                            Err(SyncError::OutsideSyncRoot { path: p.clone() }),
                        )
                    })
                    .collect();
            }
        }

        match self.direction {
            TransferDirection::Push => {
                let dest_root_str = self.dest_file_root.to_str().unwrap_or_default();
                self.backend
                    .delete_batch(dest_root_str, relative_paths)
                    .await
                    .into_iter()
                    .map(|(k, v)| (k, v.map_err(Into::into)))
                    .collect()
            }
            TransferDirection::Pull => {
                // Pull direction: dest is local filesystem — delete individually
                let mut results = HashMap::with_capacity(relative_paths.len());
                for rel in relative_paths {
                    let result = self.delete(rel).await;
                    results.insert(rel.clone(), result);
                }
                results
            }
        }
    }

    /// Whether the backend supports efficient batch operations.
    pub fn supports_batch(&self) -> bool {
        self.backend.supports_batch()
    }

    /// Check whether the source file exists for this route.
    ///
    /// - Local source: uses `tokio::fs::try_exists`
    /// - Remote source: uses `src_shell` to run `test -f <path>`
    ///
    /// Returns `Ok(true)` if file exists, `Ok(false)` if not.
    pub async fn src_file_exists(&self, relative_path: &str) -> Result<bool, SyncError> {
        Self::validate_relative_path(relative_path)?;
        let full_path = self.src_file_root.join(relative_path);

        match &self.src_shell {
            None => {
                // Local source: filesystem check
                tokio::fs::try_exists(&full_path)
                    .await
                    .map_err(SyncError::from)
            }
            Some(shell) => {
                // Remote source: `test -f <path>` via shell
                let path_str = full_path.to_str().ok_or_else(|| -> SyncError {
                    InfraError::Transfer {
                        reason: format!(
                            "src path is not valid UTF-8: {}",
                            full_path.to_string_lossy()
                        ),
                    }
                    .into()
                })?;
                let output = shell.exec(&["test", "-f", path_str], Some(10)).await?;
                Ok(output.success)
            }
        }
    }

    // --- internal helpers ---

    fn validate_relative_path(path: &str) -> Result<(), SyncError> {
        let path = path.trim_start_matches('/');
        if path.split('/').any(|seg| seg == "..") {
            return Err(SyncError::OutsideSyncRoot {
                path: path.to_string(),
            });
        }
        Ok(())
    }

    /// Safely join a root path with a relative path.
    ///
    /// Trims leading `/` from the relative part to prevent `PathBuf::join`
    /// from replacing the root entirely (Unix absolute path behaviour).
    pub(crate) fn safe_join(root: &Path, relative: &str) -> PathBuf {
        root.join(relative.trim_start_matches('/'))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn safe_join_normal() {
        assert_eq!(
            TransferRoute::safe_join(Path::new("vdsl/output"), "images/001.png"),
            PathBuf::from("vdsl/output/images/001.png")
        );
    }

    #[test]
    fn safe_join_trailing_slash() {
        assert_eq!(
            TransferRoute::safe_join(Path::new("root/"), "file.png"),
            PathBuf::from("root/file.png")
        );
    }

    #[test]
    fn safe_join_leading_slash() {
        assert_eq!(
            TransferRoute::safe_join(Path::new("root"), "/file.png"),
            PathBuf::from("root/file.png")
        );
    }

    #[test]
    fn safe_join_empty_root() {
        assert_eq!(
            TransferRoute::safe_join(Path::new(""), "file.png"),
            PathBuf::from("file.png")
        );
    }

    #[test]
    fn safe_join_both_slashes() {
        assert_eq!(
            TransferRoute::safe_join(Path::new("root/"), "/file.png"),
            PathBuf::from("root/file.png")
        );
    }

    #[test]
    fn validate_rejects_traversal() {
        assert!(TransferRoute::validate_relative_path("../../etc/passwd").is_err());
        assert!(TransferRoute::validate_relative_path("foo/../bar").is_err());
        assert!(TransferRoute::validate_relative_path("..").is_err());
    }

    #[test]
    fn validate_allows_safe_paths() {
        assert!(TransferRoute::validate_relative_path("images/001.png").is_ok());
        assert!(TransferRoute::validate_relative_path("./valid").is_ok());
        assert!(TransferRoute::validate_relative_path("a/.../b").is_ok());
        assert!(TransferRoute::validate_relative_path("").is_ok());
    }
}