quilt-rs 0.24.0

Rust library for accessing Quilt data packages.
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
use std::collections::HashMap;
use std::collections::VecDeque;
use std::path::Path;
use std::path::PathBuf;
use tokio::fs::File;

use tracing::debug;
use tracing::info;
use tracing::warn;

use crate::checksum::verify_hash;
use crate::checksum::Crc64Hash;
use crate::checksum::Sha256ChunkedHash;
use crate::io::manifest::resolve_latest;
use crate::io::remote::HostChecksums;
use crate::io::remote::HostConfig;
use crate::io::remote::Remote;
use crate::io::storage::Storage;
use crate::lineage::Change;
use crate::lineage::ChangeSet;
use crate::lineage::InstalledPackageStatus;
use crate::lineage::PackageLineage;
use crate::manifest::Row;
use crate::manifest::Table;
use crate::Error;
use crate::Res;

/// Refreshes the tracked `latest_hash` property in lineage.json
pub async fn refresh_latest_hash(
    mut lineage: PackageLineage,
    remote: &impl Remote,
) -> Res<PackageLineage> {
    let latest = resolve_latest(
        remote,
        &lineage.remote.catalog,
        &lineage.remote.clone().into(),
    )
    .await?;
    if lineage.latest_hash == latest.hash {
        return Ok(lineage);
    }
    lineage.latest_hash = latest.hash;
    Ok(lineage)
}

#[derive(Debug)]
enum WorkdirFile {
    Tracked(File, Row),
    NotTracked(File, Row),
    New(File),
    Removed(Row),
    UnSupported,
}

async fn locate_files_in_package_home(
    storage: &(impl Storage + Sync),
    manifest: &Table,
    package_home: impl AsRef<Path>,
    mut tracked_paths: HashMap<PathBuf, Row>,
) -> Res<Vec<(PathBuf, WorkdirFile)>> {
    let mut queue = VecDeque::new();
    queue.push_back(package_home.as_ref().to_path_buf());

    let mut files = Vec::new();

    while let Some(dir) = queue.pop_front() {
        let mut dir_entries = match storage.read_dir(&dir).await {
            Ok(dir_entries) => dir_entries,
            Err(err) => {
                warn!("❌ Failed to read directory {}: {}", dir.display(), err);
                continue;
            }
        };

        while let Some(dir_entry) = dir_entries.next_entry().await? {
            let file_path = dir_entry.path();

            let file_type = dir_entry.file_type().await?;
            if !file_type.is_file() {
                if file_type.is_dir() {
                    queue.push_back(file_path);
                } else {
                    // TODO: handle symlinks
                    files.push((file_path, WorkdirFile::UnSupported));
                }
                continue;
            }

            let file = storage.open_file(&file_path).await?;
            let logical_key = file_path.strip_prefix(&package_home)?.to_path_buf();
            if let Some(row) = tracked_paths.remove(&logical_key) {
                files.push((logical_key, WorkdirFile::Tracked(file, row)));
            } else if let Some(row) = manifest.get_record(&logical_key).await? {
                files.push((logical_key, WorkdirFile::NotTracked(file, row)));
            } else {
                files.push((logical_key, WorkdirFile::New(file)));
            }
        }
    }

    for (logical_key, row) in tracked_paths {
        files.push((logical_key, WorkdirFile::Removed(row)));
    }

    Ok(files)
}

async fn fingerprint_files(
    files: Vec<(PathBuf, WorkdirFile)>,
    host_config: HostConfig,
) -> Res<ChangeSet> {
    let mut changes = ChangeSet::new();
    for (logical_key, location) in files {
        match location {
            WorkdirFile::Tracked(file, row) => {
                if let Some((size, hash)) = verify_hash(file, row.hash).await? {
                    let row = Row { hash, size, ..row };
                    changes.insert(logical_key, Change::Modified(row));
                } else {
                    // the file is tracked (in lineage "paths") and has not been modified
                }
            }
            WorkdirFile::NotTracked(file, row) => {
                if let Some((size, hash)) = verify_hash(file, row.hash).await? {
                    let row = Row { hash, size, ..row };
                    changes.insert(logical_key, Change::Modified(row));
                } else {
                    debug!(
                        "✔️ File {} matches remote manifest but is not tracked locally",
                        logical_key.display()
                    );
                }
            }
            WorkdirFile::New(file) => {
                let size = file.metadata().await?.len();
                let hash = match host_config.checksums {
                    HostChecksums::Crc64 => Crc64Hash::from_async_read(file).await?.into(),
                    HostChecksums::Sha256Chunked => {
                        Sha256ChunkedHash::from_async_read(file, size).await?.into()
                    }
                };
                let row = Row {
                    name: logical_key.clone(),
                    size,
                    hash,
                    ..Row::default()
                };
                changes.insert(logical_key, Change::Added(row));
            }
            WorkdirFile::Removed(row) => {
                changes.insert(logical_key, Change::Removed(row));
            }
            WorkdirFile::UnSupported => {
                // TODO: handle symlinks
                // TODO: changes.insert(path, Change::Broken)
                warn!("❌ Unexpected file type: {}", logical_key.display());
            }
        }
    }
    Ok(changes)
}

/// Creates the status of local modifications
/// It is used for `flow::commit` and for showing the status in UI.
pub async fn create_status(
    lineage: PackageLineage,
    storage: &(impl Storage + Sync),
    manifest: &Table,
    package_home: impl AsRef<Path>,
    host_config: HostConfig,
) -> Res<(PackageLineage, InstalledPackageStatus)> {
    info!(
        "⏳ Creating status for working directory: {}",
        package_home.as_ref().display()
    );

    // compute the status based on the following sources:
    //   - the cached manifest
    //   - paths
    //   - working directory state
    // installed entries marked as "installed" (initially as "downloading")
    // modified entries marked as "modified", etc

    debug!("⏳ Collecting paths from lineage");
    let mut orig_paths = HashMap::new();
    for path in lineage.paths.keys() {
        debug!("🔍 Checking manifest for path: {}", path.display());
        let row = manifest
            .get_record(path)
            .await?
            .ok_or(Error::ManifestPath(format!(
                "path {} not found in installed manifest",
                path.display()
            )))?;
        orig_paths.insert(path.clone(), row);
    }
    debug!("✔️ Found {} paths in lineage", orig_paths.len());

    let files = locate_files_in_package_home(storage, manifest, package_home, orig_paths).await?;
    debug!("✔️ Located files in working directory {:?}", files);
    let changes = fingerprint_files(files, host_config).await?;
    debug!("✔️ Computed file fingerprints {:?}", changes);

    debug!("⏳ Creating package status");
    let status = InstalledPackageStatus::new(lineage.clone().into(), changes);
    info!("✔️ Status created with {} changes", status.changes.len());
    Ok((lineage, status))
}

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

    use std::collections::BTreeMap;

    use crate::fixtures;
    use crate::io::storage::mocks::MockStorage;
    use crate::lineage::CommitState;
    use crate::lineage::PathState;
    use crate::lineage::UpstreamState;

    #[test(tokio::test)]
    async fn test_default_status() -> Res {
        let storage = MockStorage::default();
        let (_lineage, status) = create_status(
            PackageLineage::default(),
            &storage,
            &Table::default(),
            PathBuf::default(),
            HostConfig::default(),
        )
        .await?;
        assert_eq!(status.upstream_state, UpstreamState::default());
        assert!(status.changes.is_empty());
        Ok(())
    }

    #[test(tokio::test)]
    async fn test_behind() -> Res {
        let lineage = PackageLineage {
            commit: Some(CommitState {
                hash: "AAA".to_string(),
                ..CommitState::default()
            }),
            base_hash: "AAA".to_string(),
            latest_hash: "BBB".to_string(),
            ..PackageLineage::default()
        };

        let (_lineage, status) = create_status(
            lineage,
            &MockStorage::default(),
            &Table::default(),
            PathBuf::default(),
            HostConfig::default(),
        )
        .await?;
        assert_eq!(status.upstream_state, UpstreamState::Behind);
        Ok(())
    }

    #[test(tokio::test)]
    async fn test_ahead() -> Res {
        let lineage = PackageLineage {
            commit: Some(CommitState {
                hash: "BBB".to_string(),
                ..CommitState::default()
            }),
            base_hash: "AAA".to_string(),
            latest_hash: "AAA".to_string(),
            ..PackageLineage::default()
        };

        let (_, status) = create_status(
            lineage,
            &MockStorage::default(),
            &Table::default(),
            PathBuf::default(),
            HostConfig::default(),
        )
        .await?;
        assert_eq!(status.upstream_state, UpstreamState::Ahead);
        Ok(())
    }

    #[test(tokio::test)]
    async fn test_diverged() -> Res {
        let lineage = PackageLineage {
            commit: Some(CommitState {
                hash: "aaa".to_string(),
                ..CommitState::default()
            }),
            base_hash: "bbb".to_string(),
            latest_hash: "ccc".to_string(),
            ..PackageLineage::default()
        };

        let (_, status) = create_status(
            lineage,
            &MockStorage::default(),
            &Table::default(),
            PathBuf::default(),
            HostConfig::default(),
        )
        .await?;
        assert_eq!(status.upstream_state, UpstreamState::Diverged);
        Ok(())
    }

    #[test(tokio::test)]
    async fn test_removed_files() -> Res {
        let manifest = fixtures::manifest_with_objects_all_sizes::manifest().await?;
        let logical_key = PathBuf::from("less-then-8mb.txt");
        let record = manifest.get_record(&logical_key).await?.unwrap();
        let storage = MockStorage::default();
        let lineage = PackageLineage {
            paths: BTreeMap::from([(
                logical_key.clone(),
                PathState {
                    hash: record.hash,
                    ..PathState::default()
                },
            )]),
            ..PackageLineage::default()
        };
        let working_dir = storage.temp_dir.as_ref().join(PathBuf::from("foo/bar"));
        storage
            .write_file(
                working_dir.join(&logical_key),
                fixtures::objects::less_than_8mb(),
            )
            .await?;

        // First, we create a status and see the file is not changed
        let (_, status) = create_status(
            lineage.clone(),
            &storage,
            &manifest,
            &working_dir,
            HostConfig::default(),
        )
        .await?;
        let file_not_removed_yet = status.changes.get(&logical_key);
        assert!(file_not_removed_yet.is_none());

        // Then we remove the file and create a status again
        storage.remove_file(working_dir.join(&logical_key)).await?;
        let (_, status) = create_status(
            lineage,
            &storage,
            &manifest,
            working_dir,
            HostConfig::default(),
        )
        .await?;
        // It's "removed", because it's present in lineage and manifest,
        // but absent from file system
        let removed_file = status.changes.get(&logical_key).unwrap();
        assert!(matches!(removed_file, Change::Removed(_)));
        assert!(!storage.exists(&logical_key).await);
        Ok(())
    }

    #[test(tokio::test)]
    async fn test_added_files() -> Res {
        let lineage = PackageLineage::default();
        let manifest = Table::default();

        let storage = MockStorage::default();
        let working_dir = storage.temp_dir.as_ref().join(PathBuf::from("foo/bar"));
        let file_path = PathBuf::from("inside/package/file.pq");
        storage
            .write_file(
                working_dir.join(&file_path),
                &std::fs::read(fixtures::manifest::parquet()?)?,
            )
            .await?;

        let (_, status) = create_status(
            lineage,
            &storage,
            &manifest,
            working_dir,
            HostConfig::default(),
        )
        .await?;

        let added_file = status.changes.get(&file_path).unwrap();
        if let Change::Added(added_row) = added_file {
            let reference_row = Row {
                name: PathBuf::from("inside/package/file.pq"),
                size: 5324,
                hash: Sha256ChunkedHash::try_from("EfrtXWeClWPJ/IVKjQeAmMKhJV45/GcpjDm1IhvhJAY=")?
                    .into(),
                ..Row::default()
            };
            assert_eq!(added_row, &reference_row);
            Ok(())
        } else {
            panic!("Expected Change::Added, got {:?}", added_file)
        }
    }

    #[test(tokio::test)]
    async fn test_added_files_crc64() -> Res {
        let lineage = PackageLineage::default();
        let manifest = Table::default();

        let storage = MockStorage::default();
        let working_dir = storage.temp_dir.as_ref();
        let file_path = PathBuf::from("some.pq");
        storage
            .write_file(
                working_dir.join(&file_path),
                fixtures::objects::less_than_8mb(),
            )
            .await?;

        // Use CRC64 host configuration
        let host_config = HostConfig {
            checksums: HostChecksums::Crc64,
            host: None,
        };

        let (_, status) =
            create_status(lineage, &storage, &manifest, working_dir, host_config).await?;

        let added_file = status.changes.get(&file_path).unwrap();
        if let Change::Added(added_row) = added_file {
            let reference_row = Row {
                name: PathBuf::from("some.pq"),
                size: 16,
                hash: Crc64Hash::try_from("CRSFynAYcw4=")?.into(),
                ..Row::default()
            };
            assert_eq!(added_row, &reference_row);
            Ok(())
        } else {
            panic!("Expected Change::Added, got {:?}", added_file)
        }
    }

    // TODO: add tests for every type of chunksum
}