lenso-cli 0.4.9

Authoring CLI for Lenso Plugins and App intent.
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::{
    env, fs,
    io::Read,
    path::{Path, PathBuf},
};

use anyhow::{Context, bail};
use clap::{Args, Subcommand};
pub(crate) use lenso_app_authoring::load_resolved_app;
use lenso_app_authoring::{
    BundleMutation, add_bundle, configure_instance, prepare_bundle_mutation,
    remove_instance_difference, remove_plugin, set_instance_disabled,
};
use lenso_app_plan::authoring::PluginInstanceId;
use lenso_plugin_bundle::verify_bundle_directory;

use crate::archive::with_bundle_directory;
use crate::{
    archive::archive_bundle,
    catalog::{
        CatalogPluginRelease, DEFAULT_CATALOG_URL, download_bundle, fetch_catalog_release,
        search_catalog,
    },
};
use lenso_app_authoring::identity::{validate_plugin_id_v1, validate_release_version};

#[derive(Clone, Debug, Subcommand)]
pub(crate) enum PluginsCommand {
    /// List the Plugin Instances in the derived App.
    List(ProjectArgs),
    /// Add one exact Plugin Bundle after candidate validation.
    Add(AddArgs),
    /// Write direct configuration for one Plugin Instance.
    Configure(ConfigureArgs),
    /// Disable one Plugin Instance without deleting its configuration.
    Disable(InstanceArgs),
    /// Re-enable one disabled Plugin Instance.
    Enable(InstanceArgs),
    /// Remove one Instance difference or an entire root-supplied Plugin.
    Remove(RemoveArgs),
    /// Search immutable Plugin Releases in a catalog.
    Search(SearchArgs),
    /// Install one exact catalog Release.
    Install(CatalogMutationArgs),
    /// Replace a root Bundle with one exact catalog Release.
    Update(CatalogMutationArgs),
    /// List retained exact Releases available for rollback.
    History(HistoryArgs),
    /// Restore one retained exact Release.
    Rollback(RollbackArgs),
}

#[derive(Clone, Debug, Args)]
pub(crate) struct ProjectArgs {
    /// App project root. Defaults to the current directory.
    #[arg(long)]
    root: Option<PathBuf>,
    /// Emit a stable JSON report.
    #[arg(long)]
    json: bool,
}

#[derive(Clone, Debug, Args)]
pub(crate) struct AddArgs {
    /// Exact `.lenso-plugin` Bundle archive or legacy Bundle directory.
    bundle: PathBuf,
    /// App project root. Defaults to the current directory.
    #[arg(long)]
    root: Option<PathBuf>,
}

#[derive(Clone, Debug, Args)]
pub(crate) struct ConfigureArgs {
    /// Exact Plugin ID.
    plugin_id: String,
    /// App-local Instance key.
    #[arg(default_value = "default")]
    instance: String,
    /// TOML file to use. Omit to create an empty configuration.
    #[arg(long)]
    file: Option<PathBuf>,
    /// App project root. Defaults to the current directory.
    #[arg(long)]
    root: Option<PathBuf>,
}

#[derive(Clone, Debug, Args)]
pub(crate) struct InstanceArgs {
    /// Exact Plugin ID.
    plugin_id: String,
    /// App-local Instance key.
    #[arg(default_value = "default")]
    instance: String,
    /// App project root. Defaults to the current directory.
    #[arg(long)]
    root: Option<PathBuf>,
}

#[derive(Clone, Debug, Args)]
pub(crate) struct RemoveArgs {
    /// Exact Plugin ID.
    plugin_id: String,
    /// Remove only this Instance difference; omit to remove the whole Plugin directory.
    instance: Option<String>,
    /// App project root. Defaults to the current directory.
    #[arg(long)]
    root: Option<PathBuf>,
}

#[derive(Clone, Debug, Args)]
pub(crate) struct SearchArgs {
    /// Text matched against Plugin ID, summary, and Capability IDs.
    query: Option<String>,
    /// Plugin catalog endpoint.
    #[arg(long, default_value = DEFAULT_CATALOG_URL)]
    catalog: String,
    /// Emit a stable JSON report.
    #[arg(long)]
    json: bool,
}

#[derive(Clone, Debug, Args)]
pub(crate) struct CatalogMutationArgs {
    /// Exact Plugin ID.
    plugin_id: String,
    /// Exact immutable Release version; no implicit latest selection is performed.
    #[arg(long)]
    version: String,
    /// Plugin catalog endpoint.
    #[arg(long, default_value = DEFAULT_CATALOG_URL)]
    catalog: String,
    /// App project root. Defaults to the current directory.
    #[arg(long)]
    root: Option<PathBuf>,
}

#[derive(Clone, Debug, Args)]
pub(crate) struct HistoryArgs {
    /// Exact Plugin ID.
    plugin_id: String,
    /// App project root. Defaults to the current directory.
    #[arg(long)]
    root: Option<PathBuf>,
    /// Emit a stable JSON report.
    #[arg(long)]
    json: bool,
}

#[derive(Clone, Debug, Args)]
pub(crate) struct RollbackArgs {
    /// Exact Plugin ID.
    plugin_id: String,
    /// Exact retained Release version.
    #[arg(long)]
    version: String,
    /// App project root. Defaults to the current directory.
    #[arg(long)]
    root: Option<PathBuf>,
}

pub(crate) fn plugins(command: PluginsCommand) -> anyhow::Result<()> {
    match command {
        PluginsCommand::List(args) => list(args),
        PluginsCommand::Add(args) => add(args),
        PluginsCommand::Configure(args) => configure(args),
        PluginsCommand::Disable(args) => disable(args),
        PluginsCommand::Enable(args) => enable(args),
        PluginsCommand::Remove(args) => remove(args),
        PluginsCommand::Search(args) => search(args),
        PluginsCommand::Install(args) => install(args, false),
        PluginsCommand::Update(args) => install(args, true),
        PluginsCommand::History(args) => history(args),
        PluginsCommand::Rollback(args) => rollback(args),
    }
}

pub(crate) fn project_root(root: Option<PathBuf>) -> anyhow::Result<PathBuf> {
    root.map_or_else(
        || env::current_dir().context("read current directory"),
        |root| {
            Ok(if root.is_absolute() {
                root
            } else {
                env::current_dir()?.join(root)
            })
        },
    )
}

fn list(args: ProjectArgs) -> anyhow::Result<()> {
    let root = project_root(args.root)?;
    let resolved = load_resolved_app(&root)?;
    if args.json {
        let instances = resolved
            .instances()
            .iter()
            .map(|instance| {
                serde_json::json!({
                    "id": instance.id().to_string(),
                    "source": format!("{:?}", instance.source()),
                    "plan_key": instance.plan_key(),
                })
            })
            .collect::<Vec<_>>();
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "schema_version": 1,
                "kind": "lenso.plugins-list",
                "instances": instances,
            }))?
        );
    } else {
        for instance in resolved.instances() {
            println!("{}\t{:?}", instance.id(), instance.source());
        }
    }
    Ok(())
}

fn add(args: AddArgs) -> anyhow::Result<()> {
    let bundle = args.bundle.clone();
    with_bundle_directory(&bundle, |directory| add_from_directory(args, directory))
}

fn add_from_directory(args: AddArgs, bundle: &Path) -> anyhow::Result<()> {
    let root = project_root(args.root)?;
    let (plugin_id, release_version, _) = add_bundle(&root, bundle)?;
    println!("Added Plugin `{plugin_id}` {release_version}.");
    Ok(())
}

fn configure(args: ConfigureArgs) -> anyhow::Result<()> {
    let root = project_root(args.root)?;
    let bytes = args.file.map_or_else(
        || Ok(Vec::new()),
        |path| fs::read(&path).with_context(|| format!("read {}", path.display())),
    )?;
    configure_instance(&root, &args.plugin_id, &args.instance, &bytes)?;
    let id = PluginInstanceId::new(&args.plugin_id, &args.instance);
    println!("Configured Plugin Instance `{id}`.");
    Ok(())
}

fn disable(args: InstanceArgs) -> anyhow::Result<()> {
    set_disabled(args, true)
}

fn enable(args: InstanceArgs) -> anyhow::Result<()> {
    set_disabled(args, false)
}

fn set_disabled(args: InstanceArgs, disabled_state: bool) -> anyhow::Result<()> {
    let root = project_root(args.root)?;
    set_instance_disabled(&root, &args.plugin_id, &args.instance, disabled_state)?;
    let id = PluginInstanceId::new(&args.plugin_id, &args.instance);
    if disabled_state {
        println!("Disabled Plugin Instance `{id}`.");
    } else {
        println!("Enabled Plugin Instance `{id}`.");
    }
    Ok(())
}

fn remove(args: RemoveArgs) -> anyhow::Result<()> {
    let root = project_root(args.root)?;
    if let Some(instance) = args.instance {
        remove_instance_difference(&root, &args.plugin_id, &instance)?;
        println!(
            "Removed Plugin Instance difference `{}/{instance}`.",
            args.plugin_id
        );
    } else {
        let (_, trash) = remove_plugin(&root, &args.plugin_id)?;
        println!(
            "Removed Plugin `{}`; recoverable at {}.",
            args.plugin_id,
            trash.display()
        );
    }
    Ok(())
}

fn search(args: SearchArgs) -> anyhow::Result<()> {
    let query = args.query.unwrap_or_default().to_lowercase();
    let mut releases = search_catalog(&args.catalog, &query)?
        .into_iter()
        .filter(|release| {
            query.is_empty()
                || release.plugin_id.to_lowercase().contains(&query)
                || release.summary.to_lowercase().contains(&query)
                || release
                    .capabilities
                    .iter()
                    .any(|capability| capability.to_lowercase().contains(&query))
        })
        .collect::<Vec<_>>();
    releases.sort_by(|left, right| {
        (&left.plugin_id, &left.version).cmp(&(&right.plugin_id, &right.version))
    });
    if args.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "schema_version": 1,
                "kind": "lenso.plugins-search",
                "catalog": args.catalog,
                "releases": releases.iter().map(catalog_release_json).collect::<Vec<_>>(),
            }))?
        );
    } else if releases.is_empty() {
        println!("No installable Plugin Releases matched.");
    } else {
        for release in releases {
            println!(
                "{}@{}\t{}",
                release.plugin_id, release.version, release.summary
            );
        }
    }
    Ok(())
}

fn install(args: CatalogMutationArgs, replace: bool) -> anyhow::Result<()> {
    validate_plugin_id_v1(&args.plugin_id)?;
    validate_release_version(&args.version)?;
    let root = project_root(args.root)?;
    let matches = fetch_catalog_release(&args.catalog, &args.plugin_id, &args.version)?
        .into_iter()
        .filter(|release| release.plugin_id == args.plugin_id && release.version == args.version)
        .collect::<Vec<_>>();
    let [release] = matches.as_slice() else {
        bail!(
            "catalog must contain exactly one `{}` Release at version `{}`; found {}",
            args.plugin_id,
            args.version,
            matches.len()
        );
    };
    let mut temporary = tempfile::NamedTempFile::new().context("stage catalog Plugin Bundle")?;
    download_bundle(release, temporary.as_file_mut())?;
    with_bundle_directory(temporary.path(), |bundle| {
        install_catalog_bundle(&root, release, bundle, temporary.path(), replace)
    })?;
    println!(
        "{} Plugin `{}` {}.",
        if replace { "Updated" } else { "Installed" },
        release.plugin_id,
        release.version
    );
    Ok(())
}

fn install_catalog_bundle(
    root: &Path,
    release: &CatalogPluginRelease,
    bundle: &Path,
    archive: &Path,
    replace: bool,
) -> anyhow::Result<()> {
    let mutation = if replace {
        BundleMutation::Replace
    } else {
        BundleMutation::Add
    };
    let prepared = prepare_bundle_mutation(root, bundle, mutation)?;
    let verified = prepared.verified();
    if verified.plugin_id != release.plugin_id || verified.release_version != release.version {
        bail!("catalog identity does not match the verified Plugin Bundle");
    }
    if verified.manifest_digest != release.manifest_digest {
        bail!("catalog manifest digest does not match the verified Plugin Bundle");
    }
    if replace {
        retain_current_bundle(root, &release.plugin_id, prepared.destination())?;
    }
    retain_archive(root, &release.plugin_id, &release.version, archive)?;
    prepared.commit()?;
    Ok(())
}

fn history(args: HistoryArgs) -> anyhow::Result<()> {
    validate_existing_cli_plugin_id(&args.plugin_id)?;
    let root = project_root(args.root)?;
    let directory = plugin_store(&root, &args.plugin_id);
    let mut versions = match fs::read_dir(&directory) {
        Ok(entries) => entries
            .collect::<Result<Vec<_>, _>>()?
            .into_iter()
            .filter_map(|entry| {
                entry
                    .path()
                    .file_stem()
                    .and_then(|stem| stem.to_str())
                    .map(str::to_owned)
            })
            .collect::<Vec<_>>(),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Vec::new(),
        Err(error) => return Err(error.into()),
    };
    versions.sort();
    if args.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "schema_version": 1,
                "kind": "lenso.plugins-history",
                "plugin_id": args.plugin_id,
                "versions": versions,
            }))?
        );
    } else if versions.is_empty() {
        println!("No retained Releases for `{}`.", args.plugin_id);
    } else {
        for version in versions {
            println!("{}@{}", args.plugin_id, version);
        }
    }
    Ok(())
}

fn rollback(args: RollbackArgs) -> anyhow::Result<()> {
    validate_existing_cli_plugin_id(&args.plugin_id)?;
    validate_release_version(&args.version)?;
    let root = project_root(args.root)?;
    let archive =
        plugin_store(&root, &args.plugin_id).join(format!("{}.lenso-plugin", args.version));
    if !archive.is_file() {
        bail!(
            "retained Plugin Release is unavailable: {}",
            archive.display()
        );
    }
    with_bundle_directory(&archive, |bundle| {
        let prepared = prepare_bundle_mutation(&root, bundle, BundleMutation::Restore)?;
        let verified = prepared.verified();
        if verified.plugin_id != args.plugin_id || verified.release_version != args.version {
            bail!("retained Plugin Release identity is invalid");
        }
        retain_current_bundle(&root, &args.plugin_id, prepared.destination())?;
        prepared.commit()?;
        Ok(())
    })?;
    println!(
        "Rolled back Plugin `{}` to {}.",
        args.plugin_id, args.version
    );
    Ok(())
}

fn catalog_release_json(release: &CatalogPluginRelease) -> serde_json::Value {
    serde_json::json!({
        "plugin_id": release.plugin_id,
        "version": release.version,
        "summary": release.summary,
        "bundle_url": release.bundle_url,
        "bundle_digest": release.bundle_digest,
        "manifest_digest": release.manifest_digest,
        "host_targets": release.host_targets,
        "execution_classes": release.execution_classes,
        "capabilities": release.capabilities,
    })
}

fn plugin_store(root: &Path, plugin_id: &str) -> PathBuf {
    root.join(".lenso/plugin-store").join(plugin_id)
}

fn retain_archive(
    root: &Path,
    plugin_id: &str,
    version: &str,
    archive: &Path,
) -> anyhow::Result<()> {
    let destination = plugin_store(root, plugin_id).join(format!("{version}.lenso-plugin"));
    fs::create_dir_all(destination.parent().expect("store path has a parent"))?;
    if destination.exists() {
        if !archives_equal(&destination, archive)? {
            bail!("retained Plugin Release `{plugin_id}@{version}` has different immutable bytes");
        }
        return Ok(());
    }
    fs::copy(archive, &destination)?;
    Ok(())
}

fn archives_equal(left: &Path, right: &Path) -> anyhow::Result<bool> {
    let length = fs::metadata(left)?.len();
    if length != fs::metadata(right)?.len() {
        return Ok(false);
    }
    readers_equal_exact(fs::File::open(left)?, fs::File::open(right)?, length)
}

fn readers_equal_exact(
    mut left: impl Read,
    mut right: impl Read,
    mut remaining: u64,
) -> anyhow::Result<bool> {
    let mut left_buffer = vec![0_u8; 64 * 1024].into_boxed_slice();
    let mut right_buffer = vec![0_u8; 64 * 1024].into_boxed_slice();
    while remaining != 0 {
        let chunk = usize::try_from(remaining.min(left_buffer.len() as u64))?;
        left.read_exact(&mut left_buffer[..chunk])?;
        right.read_exact(&mut right_buffer[..chunk])?;
        if left_buffer[..chunk] != right_buffer[..chunk] {
            return Ok(false);
        }
        remaining -= u64::try_from(chunk)?;
    }
    let mut left_extra = [0_u8; 1];
    let mut right_extra = [0_u8; 1];
    Ok(left.read(&mut left_extra)? == 0 && right.read(&mut right_extra)? == 0)
}

fn retain_current_bundle(root: &Path, plugin_id: &str, bundle: &Path) -> anyhow::Result<()> {
    if !bundle.is_dir() {
        bail!("current Plugin Bundle is unavailable: {}", bundle.display());
    }
    let verified = verify_bundle_directory(bundle)?;
    let staging = tempfile::tempdir().context("stage retained Plugin Release")?;
    let archive = staging.path().join("current.lenso-plugin");
    archive_bundle(bundle, &archive)?;
    retain_archive(root, plugin_id, &verified.release_version, &archive)
}

fn validate_existing_cli_plugin_id(plugin_id: &str) -> anyhow::Result<()> {
    lenso_app_authoring::identity::classify_existing_plugin_id(plugin_id).map(|_| ())
}

#[cfg(test)]
mod tests {
    use std::io::{Cursor, Read};

    use super::{archives_equal, readers_equal_exact};

    struct ShortReader {
        inner: Cursor<Vec<u8>>,
        maximum: usize,
    }

    impl Read for ShortReader {
        fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
            let length = buffer.len().min(self.maximum);
            self.inner.read(&mut buffer[..length])
        }
    }

    #[test]
    fn immutable_archive_comparison_is_exact() {
        let directory = tempfile::tempdir().unwrap();
        let left = directory.path().join("left.bundle");
        let right = directory.path().join("right.bundle");
        std::fs::write(&left, vec![b'a'; 128 * 1024]).unwrap();
        std::fs::write(&right, vec![b'a'; 128 * 1024]).unwrap();
        assert!(archives_equal(&left, &right).unwrap());

        std::fs::write(&right, vec![b'a'; 128 * 1024 - 1]).unwrap();
        assert!(!archives_equal(&left, &right).unwrap());
        let mut changed = vec![b'a'; 128 * 1024];
        changed[96 * 1024] = b'b';
        std::fs::write(&right, changed).unwrap();
        assert!(!archives_equal(&left, &right).unwrap());
    }

    #[test]
    fn archive_comparison_tolerates_different_short_read_boundaries() {
        let bytes = vec![b'a'; 128 * 1024 + 17];
        let left = ShortReader {
            inner: Cursor::new(bytes.clone()),
            maximum: 7,
        };
        let right = ShortReader {
            inner: Cursor::new(bytes.clone()),
            maximum: 113,
        };

        assert!(readers_equal_exact(left, right, bytes.len() as u64).unwrap());
    }
}