quilt-rs 0.8.4

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
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
use std::collections::BTreeMap;
use std::collections::HashSet;
use std::path::Path;
use std::path::PathBuf;

use serde_json::json;
use tokio_stream::StreamExt;
use tracing::log;
use url::Url;

use crate::io::manifest::build_manifest_from_rows_stream;
use crate::io::manifest::RowsStream;
use crate::io::manifest::StreamRowsChunk;
use crate::io::storage::Storage;
use crate::lineage::Change;
use crate::lineage::CommitState;
use crate::lineage::InstalledPackageStatus;
use crate::lineage::PackageFileFingerprint;
use crate::lineage::PackageLineage;
use crate::lineage::PathState;
use crate::manifest::JsonObject;
use crate::manifest::Row;
use crate::manifest::Table;
use crate::paths;
use crate::uri::Namespace;
use crate::Error;
use crate::Res;

async fn stream_local_with_changes(
    local_manifest: &Table,
    removed: HashSet<PathBuf>,
    modified: BTreeMap<PathBuf, Row>,
    new_files: StreamRowsChunk,
) -> impl RowsStream {
    let changes_stream = local_manifest.records_stream().await.map(move |rows| {
        rows.map(|rows| {
            rows.iter()
                .filter_map(|row_res| match row_res {
                    Ok(row) => {
                        if removed.contains(&row.name) {
                            return None;
                        }
                        if let Some(modified_row) = modified.get(&row.name) {
                            return Some(Ok(modified_row.clone()));
                        }
                        Some(Ok(row.clone()))
                    }
                    Err(err) => Some(Err(Error::Table(err.to_string()))),
                })
                .collect()
        })
    });
    tokio_stream::iter(vec![Ok(new_files)]).chain(changes_stream)
}

async fn create_immutable_object_copy(
    storage: &impl Storage,
    paths: &paths::DomainPaths,
    working_dir: &Path,
    lineage: &mut PackageLineage,
    logical_key: &PathBuf,
    current: PackageFileFingerprint,
) -> Res<Row> {
    let objects_dir = paths.objects_dir();
    // FIXME: This should really be done when the domain is created.
    storage.create_dir_all(&objects_dir).await?;
    let object_dest = objects_dir.join(hex::encode(current.hash.digest()));
    let new_physical_key = Url::from_file_path(&object_dest)
        .map_err(|_| Error::Commit(format!("Failed to create URL from {:?}", &object_dest)))?
        .into();

    let row = Row {
        name: logical_key.clone(),
        place: new_physical_key,
        size: current.size,
        hash: current.hash,
        info: serde_json::Value::default(),
        meta: serde_json::Value::default(),
    };

    let work_dest = working_dir.join(logical_key);

    if !storage.exists(&object_dest).await {
        storage.copy(&work_dest, object_dest).await?;
    }
    lineage.paths.insert(
        logical_key.clone(),
        PathState {
            timestamp: storage.modified_timestamp(&work_dest).await?,
            hash: current.hash,
        },
    );
    Ok(row)
}

/// Commit new commit with new `message`, `user_meta` and all changes got from calling `flow::status`
// TODO: move `working_dir` to `paths`, and `paths` to `storage`
#[allow(clippy::too_many_arguments)]
pub async fn commit_package(
    mut lineage: PackageLineage,
    manifest: &mut Table,
    paths: &paths::DomainPaths,
    storage: &(impl Storage + Sync),
    working_dir: PathBuf,
    status: InstalledPackageStatus,
    namespace: Namespace,
    message: String,
    user_meta: Option<JsonObject>,
) -> Res<PackageLineage> {
    log::debug!("commit: {message:?}, {user_meta:?}");
    // create a new manifest based on the stored version

    // for each modified file:
    //   - compute the new hash
    //   - store in the identity cache at $LOCAL/.quilt/objects/<hash>
    //   - update the modified entries in the manifest with the new physical keys
    //     pointing to the new objects in the identity cache
    //   - ? set entry.meta.pulled_hashes to previous object hash?
    //   - ? set entry.meta.remote_key to the remote's physical key?

    // compute the new top hash
    // store the new manifest under the new top hash at $LOCAL/.quilt/packages/<hash>
    // XXX: prefix with the namespace?
    // XXX: what to do on collisions?
    //      e.g. when a file was changed, committed, and then reverted

    // store revision pointers to the newly created manifest
    //   - in the local registry??
    //   - in the lineage
    //     - commit:
    //       - timestamp
    //       - user ?
    //       - multihash: new_top_hash
    //       - pulled_hashes: [old_top_hash] ?
    //       - paths:
    //         - [modified file's path]:
    //           - multihash
    //           # XXX: do we actually need this? can be inferred from namespace + logical key
    //           - remote_key: "s3://..." # no version id
    //           - local_key: $LOCAL/.quilt/objects/<hash>
    //           - pulled_hashes: [old_hash] ?
    // NOTE: each commit MUST include all paths from prior commits
    //       (since the last pull, until reset by a sync)

    let mut modified_keys = BTreeMap::new();
    let mut removed_keys = HashSet::new();
    let mut new_files = Vec::new();
    for (logical_key, state) in status.changes {
        match state {
            Change::Removed(row) => {
                lineage.paths.remove(&row.name);
                removed_keys.insert(row.name);
            }
            Change::Added(current) => {
                let added = create_immutable_object_copy(
                    storage,
                    paths,
                    &working_dir,
                    &mut lineage,
                    &logical_key,
                    current,
                )
                .await?;
                new_files.push(Ok(added))
            }
            Change::Modified(current) => {
                let modified = create_immutable_object_copy(
                    storage,
                    paths,
                    &working_dir,
                    &mut lineage,
                    &logical_key,
                    current,
                )
                .await?;
                modified_keys.insert(logical_key.clone(), modified);
            }
        }
    }
    let mut header = manifest.get_header().await?;

    header.info = json!({
        "message": message,
        "version": "v0",
    });
    if let Some(user_meta) = user_meta {
        header.meta = user_meta.into();
    }

    let stream = stream_local_with_changes(manifest, removed_keys, modified_keys, new_files).await;
    let manifest_path = |t: &str| paths.installed_manifest(&namespace, t);
    let (_, new_top_hash) =
        build_manifest_from_rows_stream(storage, manifest_path, header, stream).await?;

    let mut prev_hashes = Vec::new();
    if let Some(commit) = lineage.commit {
        prev_hashes.push(commit.hash.to_owned());
        prev_hashes.extend(commit.prev_hashes.to_owned());
    }
    let commit = CommitState {
        hash: new_top_hash,
        timestamp: chrono::Utc::now(),
        prev_hashes,
    };
    lineage.commit = Some(commit);

    Ok(lineage)
}

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

    use std::collections::BTreeMap;

    use crate::lineage::Change;
    use crate::mocks;

    // NOTE: Tests use "/" path for working directory, because it then parsed with Url and have to be absolute path

    #[tokio::test]
    async fn test_commit() -> Res {
        let storage = mocks::storage::MockStorage::default();

        let commit_message = "Lorem ipsum".to_string();
        let mut user_meta = serde_json::Map::new();
        user_meta.insert(
            "lorem".to_string(),
            serde_json::Value::String("ipsum".to_string()),
        );

        let lineage = PackageLineage::default();
        assert!(lineage.commit.is_none());
        let lineage = commit_package(
            lineage,
            &mut Table::default(),
            &paths::DomainPaths::default(),
            &storage,
            PathBuf::default(),
            InstalledPackageStatus::default(),
            ("foo", "bar").into(),
            commit_message,
            Some(user_meta),
        )
        .await?;
        let hash = "56c329d2390c9c6efedb698f47b75f096112c89a7751d55a426507ec6c432897";
        assert!(
            storage
                .exists(&PathBuf::from(format!(".quilt/installed/foo/bar/{}", hash)))
                .await
        );
        assert_eq!(lineage.commit.unwrap().hash, hash.to_string());
        Ok(())
    }

    #[tokio::test]
    async fn test_removing_and_commit() -> Res {
        let storage = mocks::storage::MockStorage::default();

        let commit_message = "Lorem ipsum".to_string();
        let mut user_meta = serde_json::Map::new();
        user_meta.insert(
            "lorem".to_string(),
            serde_json::Value::String("ipsum".to_string()),
        );
        let status = InstalledPackageStatus {
            changes: BTreeMap::from([(
                PathBuf::from("foo"),
                Change::Removed(Row {
                    name: PathBuf::from("foo"),
                    ..Row::default()
                }),
            )]),
            ..InstalledPackageStatus::default()
        };

        let lineage = mocks::lineage::with_paths(vec![PathBuf::from("foo")]);
        let mut manifest = mocks::manifest::with_record_keys(vec![PathBuf::from("foo")]);

        assert!(
            lineage.commit.is_none(),
            "Initial lineage has commit already"
        );
        assert!(
            lineage.paths.contains_key(&PathBuf::from("foo")),
            "Initial lineage doesn't have testing path"
        );

        let lineage = commit_package(
            lineage,
            &mut manifest,
            &paths::DomainPaths::default(),
            &storage,
            PathBuf::default(),
            status,
            ("foo", "bar").into(),
            commit_message,
            Some(user_meta),
        )
        .await?;

        let hash = "56c329d2390c9c6efedb698f47b75f096112c89a7751d55a426507ec6c432897";
        assert!(
            !lineage.paths.contains_key(&PathBuf::from("foo")),
            "Commited lineage still has a path, that should be clear after commit"
        );
        assert!(
            storage
                .exists(&PathBuf::from(format!(".quilt/installed/foo/bar/{}", hash)))
                .await,
            "Registry doesn't have installed package with a new hash"
        );
        assert_eq!(lineage.commit.unwrap().hash, hash.to_string());

        Ok(())
    }

    #[tokio::test]
    async fn test_adding_and_commit() -> Res {
        let storage = mocks::storage::MockStorage::default();
        storage
            .write_file(PathBuf::from("/working-dir/bar"), &Vec::new())
            .await?;

        let status = InstalledPackageStatus {
            changes: BTreeMap::from([(
                PathBuf::from("bar"),
                Change::Added(mocks::status::package_file_fingerprint()),
            )]),
            ..InstalledPackageStatus::default()
        };

        let lineage = PackageLineage::default();
        let mut manifest = mocks::manifest::with_record_keys(vec![PathBuf::from("foo")]);

        assert!(
            lineage.commit.is_none(),
            "Initial lineage has commit already"
        );
        assert!(
            !lineage.paths.contains_key(&PathBuf::from("bar")),
            "Initial lineage has path, but shouldn't because we test _new_ file"
        );

        let lineage = commit_package(
            lineage,
            &mut manifest,
            &paths::DomainPaths::new(PathBuf::from("/")),
            &storage,
            PathBuf::from("/working-dir"),
            status,
            ("foo", "bar").into(),
            "Lorem ipsum".to_string(),
            None,
        )
        .await?;

        let hash = "7065646573747269616e";
        assert!(
            lineage.paths.contains_key(&PathBuf::from("bar")),
            "Commited lineage doesn't have path, but should have. We added new file and it should be there."
        );
        assert!(
            storage
                .exists(&PathBuf::from(format!("/.quilt/objects/{}", hash)))
                .await,
            "Registry doesn't have installed path"
        );
        assert_eq!(
            lineage.commit.unwrap().hash,
            // NOTE: I copied this hash from the test result itself.
            //       I don't know what is the right hash
            "5819856fad67101036f115a273d7444059f403e37d51a9e3e4afa92d7d12786f"
        );

        Ok(())
    }

    // It is no longer reproducible in tests
    // and I doubt it ever could be reproducible at all
    // TODO: anyway it makes sense to add some sanity checks
    //       even for imposible states
    #[ignore]
    #[tokio::test]
    async fn test_adding_manifest_already_has_it() -> Res {
        let storage = mocks::storage::MockStorage::default();
        storage
            .write_file(PathBuf::from("foo"), &Vec::new())
            .await?;

        let status = InstalledPackageStatus {
            changes: BTreeMap::from([(
                PathBuf::from("foo"),
                Change::Added(PackageFileFingerprint::default()),
            )]),
            ..InstalledPackageStatus::default()
        };

        let lineage = mocks::lineage::with_paths(vec![PathBuf::from("foo")]);
        let mut manifest = mocks::manifest::with_record_keys(vec![PathBuf::from("foo")]);

        let result = commit_package(
            lineage,
            &mut manifest,
            &paths::DomainPaths::new(PathBuf::from("/")),
            &storage,
            PathBuf::default(),
            status,
            ("foo", "bar").into(),
            "Lorem ipsum".to_string(),
            None,
        )
        .await;

        assert_eq!(
            result.unwrap_err().to_string(),
            r#"Commit error: cannot overwrite "foo""#
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_modifying_and_commit() -> Res {
        let storage = mocks::storage::MockStorage::default();
        storage
            .write_file(PathBuf::from("/working-dir/bar"), &Vec::new())
            .await?;

        let status = InstalledPackageStatus {
            changes: BTreeMap::from([(
                PathBuf::from("bar"),
                Change::Modified(PackageFileFingerprint {
                    size: 0,
                    hash: multihash::Multihash::wrap(0xb510, b"walker")?,
                }),
            )]),
            ..InstalledPackageStatus::default()
        };

        let lineage = mocks::lineage::with_paths(vec![PathBuf::from("bar")]);
        let mut manifest = mocks::manifest::with_record_keys(vec![PathBuf::from("bar")]);

        assert!(
            lineage.commit.is_none(),
            "Initial lineage has commit already"
        );
        assert!(
            lineage.paths.contains_key(&PathBuf::from("bar")),
            "Initial lineage doesn't have path, but should because we test installed and modified file"
        );

        let lineage = commit_package(
            lineage,
            &mut manifest,
            &paths::DomainPaths::new(PathBuf::from("/")),
            &storage,
            PathBuf::from("/working-dir"),
            status,
            ("foo", "bar").into(),
            "Lorem ipsum".to_string(),
            None,
        )
        .await?;

        let hash = "77616c6b6572";
        assert!(
            lineage.paths.contains_key(&PathBuf::from("bar")),
            "Commited lineage doesn't have path, but should have. We added new file and it should be there."
        );
        assert!(
            storage
                .exists(&PathBuf::from(format!("/.quilt/objects/{}", hash)))
                .await,
            "Registry doesn't have installed path"
        );
        assert_eq!(
            lineage.commit.unwrap().hash,
            // NOTE: I copied this hash from the test result itself.
            //       I don't know what is the right hash
            "48e56751fda714b87fd3e5cb0a496cd0daa6d76ac45f0a89c5dc4c3fbbfe522e"
        );

        Ok(())
    }
}