openjd-snapshots 0.1.2

[Experimental] Job attachments snapshot library for content-addressed file tree operations. The v2023 on-disk manifest format is stable and used by AWS Deadline Cloud; the v2025 format is an experimental draft.
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// Copyright by contributors to this project.
// SPDX-License-Identifier: (Apache-2.0 OR MIT)

use crate::manifest::{AbsSnapshot, Manifest, Snapshot, SymlinkPolicy};
use crate::ops::subtree::{subtree_rel_snapshot, subtree_snapshot};
use crate::path_util::{is_absolute_path, normalize_path};
use tracing::debug;

pub struct PartitionOptions {
    pub roots: Option<Vec<String>>,
    pub referenced_paths: Option<Vec<String>>,
    pub symlink_policy: SymlinkPolicy,
}

impl Default for PartitionOptions {
    fn default() -> Self {
        Self {
            roots: None,
            referenced_paths: None,
            symlink_policy: SymlinkPolicy::CollapseEscaping,
        }
    }
}

/// Returns the longest common directory prefix of the given paths.
fn longest_common_prefix(dirs: &[&str]) -> String {
    if dirs.is_empty() {
        return String::new();
    }
    if dirs.len() == 1 {
        return dirs[0].to_string();
    }

    let parts: Vec<Vec<&str>> = dirs.iter().map(|p| p.split('/').collect()).collect();
    let min_len = parts.iter().map(|p| p.len()).min().unwrap_or(0);
    let mut common = Vec::new();

    for i in 0..min_len {
        let component = parts[0][i];
        if parts.iter().all(|p| p[i] == component) {
            common.push(component);
        } else {
            break;
        }
    }

    // For absolute paths, splitting "/a/b" gives ["", "a", "b"].
    // If only the empty-string prefix matched, the common root is "/".
    if common.len() == 1 && common[0].is_empty() {
        return "/".to_string();
    }
    common.join("/")
}

fn parent_dir(path: &str) -> String {
    match path.rfind('/') {
        Some(0) => "/".to_string(),
        Some(pos) => path[..pos].to_string(),
        None => String::new(),
    }
}

/// Collect all directory paths relevant for root determination.
fn all_dir_paths_generic<P: Clone, K: Clone>(manifest: &Manifest<P, K>) -> Vec<String> {
    let mut dirs = std::collections::HashSet::new();
    for f in &manifest.files {
        dirs.insert(parent_dir(&f.path));
    }
    for d in &manifest.dirs {
        dirs.insert(d.path.clone());
    }
    dirs.into_iter().collect()
}

fn find_root_for_path<'a>(path: &str, roots: &'a [String]) -> Option<&'a str> {
    roots.iter().find_map(|r| {
        let r_str = r.as_str();
        if r_str == "." {
            // "." root matches everything in a relative manifest
            Some(r_str)
        } else if path == r_str || path.starts_with(&format!("{r}/")) {
            Some(r_str)
        } else {
            None
        }
    })
}

fn validate_no_nested_roots(roots: &[String]) -> crate::Result<()> {
    for (i, a) in roots.iter().enumerate() {
        for (j, b) in roots.iter().enumerate() {
            if i != j && (a.starts_with(&format!("{b}/")) || b.starts_with(&format!("{a}/"))) {
                return Err(crate::SnapshotError::Validation(format!(
                    "root '{a}' is a subpath of root '{b}'"
                )));
            }
        }
    }
    Ok(())
}

/// Detect whether the manifest uses absolute paths by checking the first file or dir entry.
fn manifest_is_absolute<P: Clone, K: Clone>(manifest: &Manifest<P, K>) -> Option<bool> {
    manifest
        .files
        .first()
        .map(|f| is_absolute_path(&f.path))
        .or_else(|| manifest.dirs.first().map(|d| is_absolute_path(&d.path)))
}

/// Validate that option paths match the manifest's path style.
fn validate_path_style<P: Clone, K: Clone>(
    manifest: &Manifest<P, K>,
    options: &PartitionOptions,
) -> crate::Result<()> {
    let manifest_abs = match manifest_is_absolute(manifest) {
        Some(v) => v,
        None => return Ok(()), // empty manifest, nothing to validate
    };

    if let Some(ref roots) = options.roots {
        for r in roots {
            let root_abs = is_absolute_path(r);
            if root_abs && !manifest_abs {
                return Err(crate::SnapshotError::Validation(
                    "absolute root with relative manifest paths".into(),
                ));
            }
            if !root_abs && manifest_abs {
                return Err(crate::SnapshotError::Validation(
                    "relative root with absolute manifest paths".into(),
                ));
            }
        }
    }

    if let Some(ref rp) = options.referenced_paths {
        for p in rp {
            let rp_abs = is_absolute_path(p);
            if rp_abs != manifest_abs {
                return Err(crate::SnapshotError::Validation(
                    "absolute referenced_paths with relative manifest paths".into(),
                ));
            }
        }
    }

    Ok(())
}

/// Group remaining directory paths into roots.
fn group_into_roots(paths: &[&str]) -> Vec<String> {
    if paths.is_empty() {
        return vec![];
    }
    if paths.len() == 1 {
        return vec![paths[0].to_string()];
    }

    let prefix = longest_common_prefix(paths);
    if !prefix.is_empty() && prefix != "/" {
        return vec![prefix];
    }

    let mut groups: std::collections::HashMap<String, Vec<&str>> = std::collections::HashMap::new();
    for &p in paths {
        let key = if let Some(stripped) = p.strip_prefix('/') {
            match stripped.find('/') {
                Some(pos) => p[..pos + 1].to_string(),
                None => p.to_string(),
            }
        } else {
            match p.find('/') {
                Some(pos) => p[..pos].to_string(),
                None => p.to_string(),
            }
        };
        groups.entry(key).or_default().push(p);
    }

    let mut roots: Vec<String> = groups
        .values()
        .map(|group| longest_common_prefix(group))
        .collect();
    roots.sort();
    roots.dedup();
    roots
}

fn compute_roots<P: Clone, K: Clone>(
    manifest: &Manifest<P, K>,
    options: &PartitionOptions,
) -> crate::Result<Vec<String>> {
    let is_abs = manifest_is_absolute(manifest).unwrap_or(true);

    let mut all_paths = all_dir_paths_generic(manifest);
    if let Some(ref rp) = options.referenced_paths {
        for p in rp {
            all_paths.push(normalize_path(p));
        }
    }

    let explicit_roots: Vec<String> = options
        .roots
        .as_ref()
        .map(|r| r.iter().map(|s| normalize_path(s)).collect())
        .unwrap_or_default();

    if !explicit_roots.is_empty() {
        validate_no_nested_roots(&explicit_roots)?;
    }

    let auto_roots = if explicit_roots.is_empty() {
        if all_paths.is_empty() {
            vec![]
        } else {
            // For relative manifests, root-level files have parent_dir == "".
            // Filter those out for prefix computation, then use "." if all are root-level.
            let refs: Vec<&str> = all_paths.iter().map(|s| s.as_str()).collect();
            let non_empty: Vec<&str> = refs.iter().copied().filter(|s| !s.is_empty()).collect();
            if non_empty.is_empty() && !is_abs {
                // All files at root level of relative manifest
                vec![".".to_string()]
            } else if non_empty.len() < refs.len() && !is_abs {
                // Mix of root-level and nested — include root-level in prefix calc as "."
                let mut with_dot = non_empty.clone();
                with_dot.push(".");
                let prefix = longest_common_prefix(&with_dot);
                if prefix.is_empty() {
                    vec![".".to_string()]
                } else {
                    vec![prefix]
                }
            } else {
                let prefix = longest_common_prefix(&refs);
                vec![prefix]
            }
        }
    } else {
        let remaining: Vec<&str> = all_paths
            .iter()
            .filter(|p| {
                let p_str = p.as_str();
                // For relative manifests, empty string means root-level
                if p_str.is_empty() && !is_abs {
                    // Check if any explicit root is "." which covers root-level
                    !explicit_roots.iter().any(|r| r == ".")
                } else {
                    find_root_for_path(p_str, &explicit_roots).is_none()
                }
            })
            .map(|s| s.as_str())
            .collect();
        if remaining.is_empty() {
            vec![]
        } else {
            group_into_roots(&remaining)
        }
    };

    let mut all_roots = explicit_roots;
    let mut sorted_auto = auto_roots;
    sorted_auto.sort();
    for r in sorted_auto {
        if !all_roots.contains(&r) {
            all_roots.push(r);
        }
    }

    Ok(all_roots)
}

/// Partitions an absolute snapshot into multiple `(root, Snapshot)` pairs.
pub fn partition_manifest(
    manifest: &AbsSnapshot,
    options: &PartitionOptions,
) -> crate::Result<Vec<(String, Snapshot)>> {
    if options.symlink_policy == SymlinkPolicy::Preserve
        || options.symlink_policy == SymlinkPolicy::TransitiveIncludeTargets
    {
        return Err(crate::SnapshotError::Validation(format!(
            "symlink_policy {} is not supported for partition",
            options.symlink_policy
        )));
    }

    validate_path_style(manifest, options)?;

    let all_roots = compute_roots(manifest, options)?;
    debug!(roots = ?all_roots, "partition roots determined");

    let mut result = Vec::new();
    for root in &all_roots {
        let snapshot = subtree_snapshot(manifest, root, options.symlink_policy)?;
        debug!(root = %root, files = snapshot.files.len(), "partitioned root");
        result.push((root.clone(), snapshot));
    }

    Ok(result)
}

/// Partitions a relative snapshot into multiple `(root, Snapshot)` pairs.
pub fn partition_rel_manifest(
    manifest: &Snapshot,
    options: &PartitionOptions,
) -> crate::Result<Vec<(String, Snapshot)>> {
    if options.symlink_policy == SymlinkPolicy::Preserve
        || options.symlink_policy == SymlinkPolicy::TransitiveIncludeTargets
    {
        return Err(crate::SnapshotError::Validation(format!(
            "symlink_policy {} is not supported for partition",
            options.symlink_policy
        )));
    }

    validate_path_style(manifest, options)?;

    let all_roots = compute_roots(manifest, options)?;

    let mut result = Vec::new();
    for root in &all_roots {
        let snapshot = subtree_rel_snapshot(manifest, root, options.symlink_policy)?;
        result.push((root.clone(), snapshot));
    }

    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hash::HashAlgorithm;
    use crate::{DirEntry, FileEntry, Manifest, DEFAULT_FILE_CHUNK_SIZE};

    fn make_abs(files: Vec<FileEntry>, dirs: Vec<DirEntry>) -> AbsSnapshot {
        Manifest::new(HashAlgorithm::Xxh128, DEFAULT_FILE_CHUNK_SIZE)
            .with_files(files)
            .with_dirs(dirs)
    }

    #[test]
    fn single_directory_auto_partitions() {
        let m = make_abs(
            vec![
                FileEntry::file("/projects/scene/a.txt", 10, 1),
                FileEntry::file("/projects/scene/b.txt", 20, 2),
            ],
            vec![],
        );
        let result = partition_manifest(&m, &PartitionOptions::default()).unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].0, "/projects/scene");
        assert_eq!(result[0].1.files.len(), 2);
    }

    #[test]
    fn multiple_dirs_under_common_root() {
        let m = make_abs(
            vec![
                FileEntry::file("/root/a/file1.txt", 10, 1),
                FileEntry::file("/root/b/file2.txt", 20, 2),
            ],
            vec![],
        );
        let result = partition_manifest(&m, &PartitionOptions::default()).unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].0, "/root");
        assert_eq!(result[0].1.files.len(), 2);
    }

    #[test]
    fn explicit_roots_partition() {
        let m = make_abs(
            vec![
                FileEntry::file("/a/file1.txt", 10, 1),
                FileEntry::file("/b/file2.txt", 20, 2),
            ],
            vec![],
        );
        let opts = PartitionOptions {
            roots: Some(vec!["/a".into(), "/b".into()]),
            ..Default::default()
        };
        let result = partition_manifest(&m, &opts).unwrap();
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].0, "/a");
        assert_eq!(result[0].1.files.len(), 1);
        assert_eq!(result[0].1.files[0].path, "file1.txt");
        assert_eq!(result[1].0, "/b");
        assert_eq!(result[1].1.files.len(), 1);
    }

    #[test]
    fn empty_partition_for_explicit_root() {
        let m = make_abs(vec![FileEntry::file("/a/file.txt", 10, 1)], vec![]);
        let opts = PartitionOptions {
            roots: Some(vec!["/a".into(), "/empty".into()]),
            ..Default::default()
        };
        let result = partition_manifest(&m, &opts).unwrap();
        assert_eq!(result.len(), 2);
        assert_eq!(result[1].0, "/empty");
        assert!(result[1].1.files.is_empty());
    }

    #[test]
    fn referenced_paths_influence_root() {
        let m = make_abs(
            vec![FileEntry::file("/projects/scene/render/out.exr", 10, 1)],
            vec![],
        );
        let opts = PartitionOptions {
            referenced_paths: Some(vec!["/projects/scene/assets/tex.png".into()]),
            ..Default::default()
        };
        let result = partition_manifest(&m, &opts).unwrap();
        assert_eq!(result.len(), 1);
        // Root should be /projects/scene (common prefix of render/ and assets/)
        assert_eq!(result[0].0, "/projects/scene");
    }

    #[test]
    fn nested_roots_rejected() {
        let m = make_abs(vec![], vec![]);
        let opts = PartitionOptions {
            roots: Some(vec!["/a".into(), "/a/b".into()]),
            ..Default::default()
        };
        assert!(partition_manifest(&m, &opts).is_err());
    }

    #[test]
    fn preserve_policy_rejected() {
        let m = make_abs(vec![], vec![]);
        let opts = PartitionOptions {
            symlink_policy: SymlinkPolicy::Preserve,
            ..Default::default()
        };
        assert!(partition_manifest(&m, &opts).is_err());
    }
}