greentic-bundle-reader 0.6.0-dev.25148332542

Read-only bundle reader for greentic-bundle SquashFS artifacts and normalized build directories.
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
use std::fmt;
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::process::Command;

use serde::{Deserialize, Serialize};

pub const BUNDLE_FORMAT_VERSION: &str = "gtbundle-v1";

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BundleManifest {
    pub format_version: String,
    pub bundle_id: String,
    pub bundle_name: String,
    pub requested_mode: String,
    pub locale: String,
    pub artifact_extension: String,
    #[serde(default)]
    pub generated_resolved_files: Vec<String>,
    #[serde(default)]
    pub generated_setup_files: Vec<String>,
    #[serde(default)]
    pub app_packs: Vec<String>,
    #[serde(default)]
    pub extension_providers: Vec<String>,
    #[serde(default)]
    pub catalogs: Vec<String>,
    #[serde(default)]
    pub hooks: Vec<String>,
    #[serde(default)]
    pub subscriptions: Vec<String>,
    #[serde(default)]
    pub capabilities: Vec<String>,
    #[serde(default)]
    pub resolved_targets: Vec<BundleResolvedTargetView>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BundleLock {
    pub schema_version: u32,
    pub bundle_id: String,
    pub requested_mode: String,
    pub execution: String,
    pub cache_policy: String,
    pub tool_version: String,
    pub build_format_version: String,
    pub workspace_root: String,
    pub lock_file: String,
    pub catalogs: Vec<CatalogLockEntry>,
    pub app_packs: Vec<DependencyLock>,
    pub extension_providers: Vec<DependencyLock>,
    pub setup_state_files: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CatalogLockEntry {
    pub requested_ref: String,
    pub resolved_ref: String,
    pub digest: String,
    pub source: String,
    pub item_count: usize,
    pub item_ids: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_path: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DependencyLock {
    pub reference: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub digest: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BundleSourceKind {
    Artifact,
    BuildDir,
}

impl BundleSourceKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Artifact => "artifact",
            Self::BuildDir => "build_dir",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BundleRuntimeSurface {
    pub format_version: String,
    pub bundle_id: String,
    pub bundle_name: String,
    pub requested_mode: String,
    pub locale: String,
    pub execution: String,
    pub cache_policy: String,
    pub workspace_root: String,
    pub lock_file: String,
    pub app_packs: Vec<BundleDependencyView>,
    pub extension_providers: Vec<BundleDependencyView>,
    pub catalogs: Vec<BundleCatalogView>,
    pub hooks: Vec<String>,
    pub subscriptions: Vec<String>,
    pub capabilities: Vec<String>,
    pub resolved_targets: Vec<BundleResolvedTargetView>,
    pub generated_resolved_files: Vec<BundleFileView>,
    pub generated_setup_files: Vec<BundleFileView>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BundleDependencyView {
    pub reference: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub digest: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BundleCatalogView {
    pub requested_ref: String,
    pub resolved_ref: String,
    pub digest: String,
    pub source: String,
    pub item_count: usize,
    pub item_ids: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_path: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BundleFileView {
    pub path: String,
    pub kind: BundleFileKind,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BundleResolvedTargetView {
    pub path: String,
    pub tenant: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub team: Option<String>,
    pub default_policy: String,
    pub tenant_gmap: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub team_gmap: Option<String>,
    #[serde(default)]
    pub app_pack_policies: Vec<BundleResolvedReferencePolicyView>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BundleResolvedReferencePolicyView {
    pub reference: String,
    pub policy: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BundleFileKind {
    Resolved,
    SetupState,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OpenedBundle {
    pub source_kind: BundleSourceKind,
    pub source_path: String,
    pub format_version: String,
    pub manifest: BundleManifest,
    pub lock: BundleLock,
}

impl OpenedBundle {
    pub fn from_parts(
        source_kind: BundleSourceKind,
        source_path: impl Into<String>,
        manifest: BundleManifest,
        lock: BundleLock,
    ) -> Result<Self, BundleReadError> {
        let opened = Self {
            source_kind,
            source_path: source_path.into(),
            format_version: manifest.format_version.clone(),
            manifest,
            lock,
        };
        opened.validate_basic_structure()?;
        Ok(opened)
    }

    pub fn runtime_surface(&self) -> BundleRuntimeSurface {
        BundleRuntimeSurface {
            format_version: self.manifest.format_version.clone(),
            bundle_id: self.manifest.bundle_id.clone(),
            bundle_name: self.manifest.bundle_name.clone(),
            requested_mode: self.manifest.requested_mode.clone(),
            locale: self.manifest.locale.clone(),
            execution: self.lock.execution.clone(),
            cache_policy: self.lock.cache_policy.clone(),
            workspace_root: self.lock.workspace_root.clone(),
            lock_file: self.lock.lock_file.clone(),
            app_packs: self
                .lock
                .app_packs
                .iter()
                .map(|entry| BundleDependencyView {
                    reference: entry.reference.clone(),
                    digest: entry.digest.clone(),
                })
                .collect(),
            extension_providers: self
                .lock
                .extension_providers
                .iter()
                .map(|entry| BundleDependencyView {
                    reference: entry.reference.clone(),
                    digest: entry.digest.clone(),
                })
                .collect(),
            catalogs: self
                .lock
                .catalogs
                .iter()
                .map(|entry| BundleCatalogView {
                    requested_ref: entry.requested_ref.clone(),
                    resolved_ref: entry.resolved_ref.clone(),
                    digest: entry.digest.clone(),
                    source: entry.source.clone(),
                    item_count: entry.item_count,
                    item_ids: entry.item_ids.clone(),
                    cache_path: entry.cache_path.clone(),
                })
                .collect(),
            hooks: self.manifest.hooks.clone(),
            subscriptions: self.manifest.subscriptions.clone(),
            capabilities: self.manifest.capabilities.clone(),
            resolved_targets: self.manifest.resolved_targets.clone(),
            generated_resolved_files: self
                .manifest
                .generated_resolved_files
                .iter()
                .map(|path| BundleFileView {
                    path: path.clone(),
                    kind: BundleFileKind::Resolved,
                })
                .collect(),
            generated_setup_files: self
                .manifest
                .generated_setup_files
                .iter()
                .map(|path| BundleFileView {
                    path: path.clone(),
                    kind: BundleFileKind::SetupState,
                })
                .collect(),
        }
    }

    pub fn validate_basic_structure(&self) -> Result<(), BundleReadError> {
        if self.manifest.format_version != BUNDLE_FORMAT_VERSION {
            return Err(BundleReadError::invalid(
                self.source_kind,
                &self.source_path,
                format!(
                    "unsupported bundle format version: {}",
                    self.manifest.format_version
                ),
            ));
        }
        if self.manifest.bundle_id.trim().is_empty() {
            return Err(BundleReadError::invalid(
                self.source_kind,
                &self.source_path,
                "bundle manifest is missing bundle_id".to_string(),
            ));
        }
        if self.lock.bundle_id.trim().is_empty() {
            return Err(BundleReadError::invalid(
                self.source_kind,
                &self.source_path,
                "bundle lock is missing bundle_id".to_string(),
            ));
        }
        if self.manifest.bundle_id != self.lock.bundle_id {
            return Err(BundleReadError::invalid(
                self.source_kind,
                &self.source_path,
                "bundle manifest and lock bundle_id do not match".to_string(),
            ));
        }
        if self.manifest.requested_mode != self.lock.requested_mode {
            return Err(BundleReadError::invalid(
                self.source_kind,
                &self.source_path,
                "bundle manifest and lock requested_mode do not match".to_string(),
            ));
        }
        if self.manifest.artifact_extension != ".gtbundle" {
            return Err(BundleReadError::invalid(
                self.source_kind,
                &self.source_path,
                format!(
                    "unsupported artifact extension: {}",
                    self.manifest.artifact_extension
                ),
            ));
        }
        if self.lock.workspace_root != "bundle.yaml" {
            return Err(BundleReadError::invalid(
                self.source_kind,
                &self.source_path,
                format!("unexpected workspace_root: {}", self.lock.workspace_root),
            ));
        }
        if self.lock.lock_file != "bundle.lock.json" {
            return Err(BundleReadError::invalid(
                self.source_kind,
                &self.source_path,
                format!("unexpected lock_file: {}", self.lock.lock_file),
            ));
        }
        if self.lock.setup_state_files != self.manifest.generated_setup_files {
            return Err(BundleReadError::invalid(
                self.source_kind,
                &self.source_path,
                "bundle manifest and lock setup state files do not match".to_string(),
            ));
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BundleReadError {
    pub kind: BundleReadErrorKind,
    pub source_kind: BundleSourceKind,
    pub source_path: String,
    pub details: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BundleReadErrorKind {
    Io,
    Invalid,
    Tool,
}

impl BundleReadError {
    fn io(source_kind: BundleSourceKind, source_path: &Path, details: String) -> Self {
        Self {
            kind: BundleReadErrorKind::Io,
            source_kind,
            source_path: source_path.display().to_string(),
            details,
        }
    }

    fn invalid(source_kind: BundleSourceKind, source_path: &str, details: String) -> Self {
        Self {
            kind: BundleReadErrorKind::Invalid,
            source_kind,
            source_path: source_path.to_string(),
            details,
        }
    }

    fn tool(source_kind: BundleSourceKind, source_path: &Path, details: String) -> Self {
        Self {
            kind: BundleReadErrorKind::Tool,
            source_kind,
            source_path: source_path.display().to_string(),
            details,
        }
    }
}

impl fmt::Display for BundleReadError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} read failed for {} ({}): {}",
            self.source_kind.as_str(),
            self.source_path,
            match self.kind {
                BundleReadErrorKind::Io => "io",
                BundleReadErrorKind::Invalid => "invalid",
                BundleReadErrorKind::Tool => "tool",
            },
            self.details
        )
    }
}

impl std::error::Error for BundleReadError {}

pub fn open_artifact(path: &Path) -> Result<OpenedBundle, BundleReadError> {
    let manifest_raw = read_artifact_file(path, "bundle-manifest.json")?;
    let lock_raw = read_artifact_file(path, "bundle-lock.json")?;
    let manifest = parse_manifest(BundleSourceKind::Artifact, path, &manifest_raw)?;
    let lock = parse_lock(BundleSourceKind::Artifact, path, &lock_raw)?;
    let opened = OpenedBundle::from_parts(
        BundleSourceKind::Artifact,
        path.display().to_string(),
        manifest,
        lock,
    )?;
    validate_artifact_contents(path, &opened)?;
    Ok(opened)
}

pub fn open_build_dir(path: &Path) -> Result<OpenedBundle, BundleReadError> {
    open_build_dir_with_source(path, path.display().to_string())
}

pub fn open_build_dir_with_source(
    path: &Path,
    source_path: impl Into<String>,
) -> Result<OpenedBundle, BundleReadError> {
    let manifest_raw = read_build_file(path, "bundle-manifest.json")?;
    let lock_raw = read_build_file(path, "bundle-lock.json")?;
    let manifest = parse_manifest(BundleSourceKind::BuildDir, path, &manifest_raw)?;
    let lock = parse_lock(BundleSourceKind::BuildDir, path, &lock_raw)?;
    let opened = OpenedBundle::from_parts(BundleSourceKind::BuildDir, source_path, manifest, lock)?;
    validate_build_dir_contents(path, &opened)?;
    Ok(opened)
}

fn read_build_file(root: &Path, name: &str) -> Result<String, BundleReadError> {
    fs::read_to_string(root.join(name)).map_err(|error| {
        BundleReadError::io(
            BundleSourceKind::BuildDir,
            root,
            format!("read {}: {error}", root.join(name).display()),
        )
    })
}

fn read_artifact_file(path: &Path, inner_path: &str) -> Result<String, BundleReadError> {
    let output = Command::new("unsquashfs")
        .args(["-cat", path.to_str().unwrap_or_default(), inner_path])
        .output()
        .map_err(|error| {
            BundleReadError::tool(
                BundleSourceKind::Artifact,
                path,
                match error.kind() {
                    ErrorKind::NotFound => "required tool `unsquashfs` was not found on PATH; install SquashFS tools to read `.gtbundle` artifacts".to_string(),
                    _ => format!("spawn unsquashfs: {error}"),
                },
            )
        })?;
    if !output.status.success() {
        return Err(BundleReadError::tool(
            BundleSourceKind::Artifact,
            path,
            format!(
                "unsquashfs failed for {}: {}",
                inner_path,
                String::from_utf8_lossy(&output.stderr).trim()
            ),
        ));
    }
    String::from_utf8(output.stdout).map_err(|error| {
        BundleReadError::invalid(
            BundleSourceKind::Artifact,
            &path.display().to_string(),
            format!("artifact entry {inner_path} is not valid utf-8: {error}"),
        )
    })
}

fn parse_manifest(
    source_kind: BundleSourceKind,
    source_path: &Path,
    raw: &str,
) -> Result<BundleManifest, BundleReadError> {
    serde_json::from_str(raw).map_err(|error| {
        BundleReadError::invalid(
            source_kind,
            &source_path.display().to_string(),
            format!("parse bundle-manifest.json: {error}"),
        )
    })
}

fn parse_lock(
    source_kind: BundleSourceKind,
    source_path: &Path,
    raw: &str,
) -> Result<BundleLock, BundleReadError> {
    serde_json::from_str(raw).map_err(|error| {
        BundleReadError::invalid(
            source_kind,
            &source_path.display().to_string(),
            format!("parse bundle-lock.json: {error}"),
        )
    })
}

fn validate_build_dir_contents(path: &Path, opened: &OpenedBundle) -> Result<(), BundleReadError> {
    ensure_path_exists(
        BundleSourceKind::BuildDir,
        path,
        &path.join("bundle.yaml"),
        "bundle.yaml",
    )?;
    for rel_path in &opened.manifest.generated_resolved_files {
        ensure_path_exists(
            BundleSourceKind::BuildDir,
            path,
            &path.join(rel_path),
            rel_path,
        )?;
    }
    for rel_path in &opened.manifest.generated_setup_files {
        ensure_path_exists(
            BundleSourceKind::BuildDir,
            path,
            &path.join(rel_path),
            rel_path,
        )?;
    }
    Ok(())
}

fn validate_artifact_contents(path: &Path, opened: &OpenedBundle) -> Result<(), BundleReadError> {
    read_artifact_file(path, "bundle.yaml")?;
    for rel_path in &opened.manifest.generated_resolved_files {
        read_artifact_file(path, rel_path)?;
    }
    for rel_path in &opened.manifest.generated_setup_files {
        read_artifact_file(path, rel_path)?;
    }
    Ok(())
}

fn ensure_path_exists(
    source_kind: BundleSourceKind,
    source_path: &Path,
    full_path: &Path,
    display_path: &str,
) -> Result<(), BundleReadError> {
    if full_path.exists() {
        return Ok(());
    }
    Err(BundleReadError::invalid(
        source_kind,
        &source_path.display().to_string(),
        format!("missing required bundle file: {display_path}"),
    ))
}

pub fn build_dir_from_artifact_source(root: &Path, bundle_id: &str) -> PathBuf {
    root.join("state")
        .join("build")
        .join(bundle_id)
        .join("normalized")
}