harn-modules 0.10.16

Cross-file module graph and import resolution utilities for Harn
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
use std::fmt;
use std::fs::{self, File, OpenOptions};
use std::io;
use std::path::{Component, Path, PathBuf};

use fs2::FileExt;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

pub const PACKAGE_STATE_DIR: &str = ".harn";
pub const PACKAGE_CURRENT_FILE: &str = "package-current.toml";
pub const PACKAGE_GENERATIONS_DIR: &str = "package-generations";
pub const PACKAGE_PUBLICATION_LOCK_FILE: &str = "package-generation.lock";
pub const PACKAGE_INSTALL_LOCK_FILE: &str = "package-install.lock";
pub const GENERATION_MANIFEST_FILE: &str = "generation.toml";
pub const GENERATION_LOCK_FILE: &str = "harn.lock";
pub const GENERATION_LEASE_FILE: &str = "lease.lock";
pub const GENERATION_PACKAGES_DIR: &str = "packages";
pub const PACKAGE_GENERATION_SCHEMA_VERSION: u32 = 1;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PackageGenerationPointer {
    pub schema_version: u32,
    pub generation: String,
}

impl PackageGenerationPointer {
    pub fn new(generation: impl Into<String>) -> Result<Self, PackageSnapshotError> {
        let generation = generation.into();
        validate_generation_id(&generation)?;
        Ok(Self {
            schema_version: PACKAGE_GENERATION_SCHEMA_VERSION,
            generation,
        })
    }

    pub fn validate(&self, path: &Path) -> Result<(), PackageSnapshotError> {
        validate_schema_version(self.schema_version, path)?;
        validate_generation_id(&self.generation)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PackageGenerationManifest {
    pub schema_version: u32,
    pub generation: String,
    pub lock_digest: String,
}

impl PackageGenerationManifest {
    pub fn new(
        generation: impl Into<String>,
        lock_digest: impl Into<String>,
    ) -> Result<Self, PackageSnapshotError> {
        let generation = generation.into();
        validate_generation_id(&generation)?;
        let lock_digest = lock_digest.into();
        validate_lock_digest(&lock_digest)?;
        Ok(Self {
            schema_version: PACKAGE_GENERATION_SCHEMA_VERSION,
            generation,
            lock_digest,
        })
    }

    pub fn validate(&self, path: &Path) -> Result<(), PackageSnapshotError> {
        validate_schema_version(self.schema_version, path)?;
        validate_generation_id(&self.generation)?;
        validate_lock_digest(&self.lock_digest)
    }
}

#[derive(Debug)]
pub struct PackageSnapshot {
    project_root: PathBuf,
    generation: String,
    generation_root: PathBuf,
    packages_root: PathBuf,
    lock_path: PathBuf,
    lock_digest: String,
    package_names: Vec<String>,
    _lease: File,
}

impl PackageSnapshot {
    /// Acquire the currently published package generation for `project_root`.
    ///
    /// The publication lock closes the pointer-to-lease race: GC cannot remove
    /// the selected generation until this reader holds its shared lease.
    pub fn acquire(project_root: &Path) -> Result<Option<Self>, PackageSnapshotError> {
        let project_root = project_root
            .canonicalize()
            .map_err(|error| PackageSnapshotError::io("canonicalize", project_root, error))?;
        let state_path = project_root.join(PACKAGE_STATE_DIR);
        if !state_path.is_dir() {
            return Ok(None);
        }
        let state_dir = canonical_directory_within(&project_root, &state_path)?;
        let pointer_path = state_dir.join(PACKAGE_CURRENT_FILE);
        let publication_lock_path = state_dir.join(PACKAGE_PUBLICATION_LOCK_FILE);
        if !publication_lock_path.exists() && !pointer_path.exists() {
            return Ok(None);
        }
        require_regular_file(&publication_lock_path)?;
        let publication_lock = open_existing_lock_file(&publication_lock_path)?;
        FileExt::lock_shared(&publication_lock)
            .map_err(|error| PackageSnapshotError::io("lock", &publication_lock_path, error))?;

        if !pointer_path.is_file() {
            return Ok(None);
        }
        require_regular_file(&pointer_path)?;

        let pointer = read_toml::<PackageGenerationPointer>(&pointer_path)?;
        pointer.validate(&pointer_path)?;
        let generations_dir =
            canonical_directory_within(&state_dir, &state_dir.join(PACKAGE_GENERATIONS_DIR))?;
        let generation_root = canonical_directory_within(
            &generations_dir,
            &generations_dir.join(&pointer.generation),
        )?;
        let lease_path = generation_root.join(GENERATION_LEASE_FILE);
        require_regular_file(&lease_path)?;
        let lease = open_existing_lock_file(&lease_path)?;
        FileExt::lock_shared(&lease)
            .map_err(|error| PackageSnapshotError::io("lock", &lease_path, error))?;

        // The generation lease now protects every immutable artifact below the
        // selected root, so GC no longer needs to be excluded.
        FileExt::unlock(&publication_lock)
            .map_err(|error| PackageSnapshotError::io("unlock", &publication_lock_path, error))?;

        let manifest_path = generation_root.join(GENERATION_MANIFEST_FILE);
        require_regular_file(&manifest_path)?;
        let manifest = read_toml::<PackageGenerationManifest>(&manifest_path)?;
        manifest.validate(&manifest_path)?;
        if manifest.generation != pointer.generation {
            return Err(PackageSnapshotError::Invalid(format!(
                "{} names generation {:?}, expected {:?}",
                manifest_path.display(),
                manifest.generation,
                pointer.generation
            )));
        }
        let packages_root = canonical_directory_within(
            &generation_root,
            &generation_root.join(GENERATION_PACKAGES_DIR),
        )?;
        let lock_path = generation_root.join(GENERATION_LOCK_FILE);
        require_regular_file(&lock_path)?;
        let lock_bytes = fs::read(&lock_path)
            .map_err(|error| PackageSnapshotError::io("read", &lock_path, error))?;
        let actual_lock_digest = package_lock_digest(&lock_bytes);
        if actual_lock_digest != manifest.lock_digest {
            return Err(PackageSnapshotError::Invalid(format!(
                "{} digest mismatch: generation manifest records {}, actual {}",
                lock_path.display(),
                manifest.lock_digest,
                actual_lock_digest
            )));
        }
        let package_names = parse_package_names(&lock_path, &lock_bytes)?;

        Ok(Some(Self {
            project_root,
            generation: pointer.generation,
            generation_root,
            packages_root,
            lock_path,
            lock_digest: manifest.lock_digest,
            package_names,
            _lease: lease,
        }))
    }

    pub fn acquire_nearest(anchor: &Path) -> Result<Option<Self>, PackageSnapshotError> {
        let mut cursor = if anchor.is_dir() {
            Some(anchor)
        } else {
            anchor.parent()
        };
        while let Some(dir) = cursor {
            if dir
                .join(PACKAGE_STATE_DIR)
                .join(PACKAGE_CURRENT_FILE)
                .is_file()
            {
                return Self::acquire(dir);
            }
            if dir.join(".git").exists() {
                break;
            }
            cursor = dir.parent();
        }
        Ok(None)
    }

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

    pub fn generation(&self) -> &str {
        &self.generation
    }

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

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

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

    pub fn lock_digest(&self) -> &str {
        &self.lock_digest
    }

    pub fn package_names(&self) -> &[String] {
        &self.package_names
    }
}

#[derive(Debug)]
pub enum PackageSnapshotError {
    Io {
        operation: &'static str,
        path: PathBuf,
        source: io::Error,
    },
    Invalid(String),
}

impl PackageSnapshotError {
    fn io(operation: &'static str, path: &Path, source: io::Error) -> Self {
        Self::Io {
            operation,
            path: path.to_path_buf(),
            source,
        }
    }
}

impl fmt::Display for PackageSnapshotError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io {
                operation,
                path,
                source,
            } => write!(
                formatter,
                "failed to {operation} {}: {source}",
                path.display()
            ),
            Self::Invalid(message) => formatter.write_str(message),
        }
    }
}

impl std::error::Error for PackageSnapshotError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io { source, .. } => Some(source),
            Self::Invalid(_) => None,
        }
    }
}

pub fn package_state_dir(project_root: &Path) -> PathBuf {
    project_root.join(PACKAGE_STATE_DIR)
}

pub fn package_generations_dir(project_root: &Path) -> PathBuf {
    package_state_dir(project_root).join(PACKAGE_GENERATIONS_DIR)
}

pub fn package_publication_lock_path(project_root: &Path) -> PathBuf {
    package_state_dir(project_root).join(PACKAGE_PUBLICATION_LOCK_FILE)
}

pub fn package_current_path(project_root: &Path) -> PathBuf {
    package_state_dir(project_root).join(PACKAGE_CURRENT_FILE)
}

pub fn generation_root(project_root: &Path, generation: &str) -> PathBuf {
    package_generations_dir(project_root).join(generation)
}

pub fn open_lock_file(path: &Path) -> Result<File, PackageSnapshotError> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .map_err(|error| PackageSnapshotError::io("create", parent, error))?;
    }
    OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(path)
        .map_err(|error| PackageSnapshotError::io("open", path, error))
}

fn open_existing_lock_file(path: &Path) -> Result<File, PackageSnapshotError> {
    OpenOptions::new()
        .read(true)
        .write(true)
        .open(path)
        .map_err(|error| PackageSnapshotError::io("open", path, error))
}

fn read_toml<T>(path: &Path) -> Result<T, PackageSnapshotError>
where
    T: for<'de> Deserialize<'de>,
{
    let source =
        fs::read_to_string(path).map_err(|error| PackageSnapshotError::io("read", path, error))?;
    toml::from_str(&source).map_err(|error| {
        PackageSnapshotError::Invalid(format!("failed to parse {}: {error}", path.display()))
    })
}

fn validate_schema_version(version: u32, path: &Path) -> Result<(), PackageSnapshotError> {
    if version == PACKAGE_GENERATION_SCHEMA_VERSION {
        Ok(())
    } else {
        Err(PackageSnapshotError::Invalid(format!(
            "unsupported {} schema version {} (expected {})",
            path.display(),
            version,
            PACKAGE_GENERATION_SCHEMA_VERSION
        )))
    }
}

pub fn validate_generation_id(generation: &str) -> Result<(), PackageSnapshotError> {
    let path = Path::new(generation);
    let mut components = path.components();
    let Some(Component::Normal(component)) = components.next() else {
        return Err(invalid_generation_id(generation));
    };
    if components.next().is_some()
        || component.to_str() != Some(generation)
        || generation.starts_with('.')
        || !generation
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
    {
        return Err(invalid_generation_id(generation));
    }
    Ok(())
}

fn invalid_generation_id(generation: &str) -> PackageSnapshotError {
    PackageSnapshotError::Invalid(format!("invalid package generation id {generation:?}"))
}

fn validate_lock_digest(digest: &str) -> Result<(), PackageSnapshotError> {
    let Some(hex) = digest.strip_prefix("sha256:") else {
        return Err(PackageSnapshotError::Invalid(format!(
            "invalid package lock digest {digest:?}"
        )));
    };
    if hex.len() != 64 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        return Err(PackageSnapshotError::Invalid(format!(
            "invalid package lock digest {digest:?}"
        )));
    }
    Ok(())
}

#[derive(Deserialize)]
struct PublishedLock {
    #[serde(default, rename = "package")]
    packages: Vec<PublishedLockEntry>,
}

#[derive(Deserialize)]
struct PublishedLockEntry {
    name: String,
}

fn parse_package_names(path: &Path, bytes: &[u8]) -> Result<Vec<String>, PackageSnapshotError> {
    let source = std::str::from_utf8(bytes).map_err(|error| {
        PackageSnapshotError::Invalid(format!("{} is not UTF-8: {error}", path.display()))
    })?;
    let lock = toml::from_str::<PublishedLock>(source).map_err(|error| {
        PackageSnapshotError::Invalid(format!("failed to parse {}: {error}", path.display()))
    })?;
    let mut names = std::collections::BTreeSet::new();
    for entry in lock.packages {
        if !is_valid_package_name(&entry.name) || !names.insert(entry.name.clone()) {
            return Err(PackageSnapshotError::Invalid(format!(
                "{} contains an invalid or duplicate package name {:?}",
                path.display(),
                entry.name
            )));
        }
    }
    Ok(names.into_iter().collect())
}

/// Return whether `name` is a safe single-component package import alias.
pub fn is_valid_package_name(name: &str) -> bool {
    !name.is_empty()
        && name != "."
        && name != ".."
        && name
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))
}

fn encode_hex(bytes: &[u8]) -> String {
    let mut encoded = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        use std::fmt::Write as _;
        let _ = write!(encoded, "{byte:02x}");
    }
    encoded
}

pub fn package_lock_digest(bytes: &[u8]) -> String {
    format!("sha256:{}", encode_hex(&Sha256::digest(bytes)))
}

fn canonical_directory_within(root: &Path, path: &Path) -> Result<PathBuf, PackageSnapshotError> {
    let canonical = path
        .canonicalize()
        .map_err(|error| PackageSnapshotError::io("canonicalize", path, error))?;
    if canonical == root || canonical.starts_with(root) {
        Ok(canonical)
    } else {
        Err(PackageSnapshotError::Invalid(format!(
            "package generation directory escapes {}: {}",
            root.display(),
            path.display()
        )))
    }
}

fn require_regular_file(path: &Path) -> Result<(), PackageSnapshotError> {
    let metadata = fs::symlink_metadata(path)
        .map_err(|error| PackageSnapshotError::io("stat", path, error))?;
    if metadata.file_type().is_file() {
        return Ok(());
    }
    Err(PackageSnapshotError::Invalid(format!(
        "package generation file is not a regular file: {}",
        path.display()
    )))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Barrier};

    fn publish_fixture(root: &Path, generation: &str, body: &str) {
        let generation_root = generation_root(root, generation);
        fs::create_dir_all(generation_root.join(GENERATION_PACKAGES_DIR)).unwrap();
        fs::write(generation_root.join(GENERATION_LOCK_FILE), body).unwrap();
        fs::write(generation_root.join(GENERATION_LEASE_FILE), []).unwrap();
        let digest = package_lock_digest(body.as_bytes());
        let manifest = PackageGenerationManifest::new(generation, digest).unwrap();
        fs::write(
            generation_root.join(GENERATION_MANIFEST_FILE),
            toml::to_string_pretty(&manifest).unwrap(),
        )
        .unwrap();
        let pointer = PackageGenerationPointer::new(generation).unwrap();
        fs::create_dir_all(package_state_dir(root)).unwrap();
        fs::write(
            package_current_path(root),
            toml::to_string_pretty(&pointer).unwrap(),
        )
        .unwrap();
        File::create(package_publication_lock_path(root)).unwrap();
    }

    #[test]
    fn snapshot_holds_generation_lease_until_drop() {
        let temp = tempfile::tempdir().unwrap();
        publish_fixture(temp.path(), "generation_a", "version = 4\n# lock a\n");

        let snapshot = PackageSnapshot::acquire(temp.path()).unwrap().unwrap();
        let lease =
            open_existing_lock_file(&snapshot.generation_root().join(GENERATION_LEASE_FILE))
                .unwrap();
        assert!(FileExt::try_lock_exclusive(&lease).is_err());

        drop(snapshot);
        FileExt::try_lock_exclusive(&lease).unwrap();
    }

    #[test]
    fn reader_selects_generation_published_before_publication_unlock() {
        let temp = tempfile::tempdir().unwrap();
        publish_fixture(temp.path(), "generation_a", "version = 4\n# lock a\n");
        let root = temp.path().to_path_buf();
        let publication = open_lock_file(&package_publication_lock_path(&root)).unwrap();
        FileExt::lock_exclusive(&publication).unwrap();

        let started = Arc::new(Barrier::new(2));
        let reader_started = Arc::clone(&started);
        let reader_root = root.clone();
        let reader = std::thread::spawn(move || {
            reader_started.wait();
            PackageSnapshot::acquire(&reader_root).unwrap().unwrap()
        });
        started.wait();

        publish_fixture(&root, "generation_b", "version = 4\n# lock b\n");
        FileExt::unlock(&publication).unwrap();

        let snapshot = reader.join().unwrap();
        assert_eq!(snapshot.generation(), "generation_b");
        assert_eq!(
            fs::read_to_string(snapshot.lock_path()).unwrap(),
            "version = 4\n# lock b\n"
        );
    }

    #[test]
    fn malformed_pointer_cannot_escape_generation_root() {
        let temp = tempfile::tempdir().unwrap();
        fs::create_dir_all(package_state_dir(temp.path())).unwrap();
        fs::write(
            package_current_path(temp.path()),
            "schema_version = 1\ngeneration = \"../outside\"\n",
        )
        .unwrap();
        File::create(package_publication_lock_path(temp.path())).unwrap();

        let error = PackageSnapshot::acquire(temp.path()).unwrap_err();
        assert!(
            error.to_string().contains("invalid package generation id"),
            "unexpected error: {error}"
        );
    }

    #[test]
    fn lock_package_name_cannot_escape_packages_root() {
        let temp = tempfile::tempdir().unwrap();
        publish_fixture(
            temp.path(),
            "generation_a",
            "version = 4\n\n[[package]]\nname = \"../outside\"\n",
        );

        let error = PackageSnapshot::acquire(temp.path()).unwrap_err();
        assert!(
            error
                .to_string()
                .contains("invalid or duplicate package name"),
            "unexpected error: {error}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn symlinked_generation_root_cannot_escape_generations_directory() {
        let temp = tempfile::tempdir().unwrap();
        publish_fixture(temp.path(), "generation_a", "version = 4\n");
        let generation = generation_root(temp.path(), "generation_a");
        let outside = temp.path().join("outside-generation");
        fs::rename(&generation, &outside).unwrap();
        std::os::unix::fs::symlink(&outside, &generation).unwrap();

        let error = PackageSnapshot::acquire(temp.path()).unwrap_err();
        assert!(
            error.to_string().contains("escapes"),
            "unexpected error: {error}"
        );
    }
}