holochain_cli_sandbox 0.7.0-dev.9

A library and CLI to help create, run and interact with sandboxed Holochain conductor environments, for testing and development purposes.
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
//! Definitions of Parser options for use in the CLI

use crate::cmds::*;
use clap::{ArgAction, Parser};
use holochain_conductor_api::conductor::paths::ConfigRootPath;
use holochain_trace::Output;
use holochain_types::prelude::InstalledAppId;
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::path::PathBuf;

const DEFAULT_APP_ID: &str = "test-app";

/// Helper for generating, running, and interacting with Holochain Conductor "sandboxes".
///
/// A sandbox is a directory containing a conductor config, databases, and keystore,
/// with a single Holochain app installed in the conductor:
/// Everything you need to quickly run your app in Holochain,
/// or create complex multi-conductor setups for testing.
#[derive(Debug, Parser)]
#[command(version, about)]
pub struct HcSandbox {
    #[command(subcommand)]
    subcommand: HcSandboxSubcommand,

    /// Instead of the normal "interactive" passphrase mode,
    /// collect the passphrase by reading stdin to the end.
    #[arg(long)]
    piped: bool,

    /// The log output option to use for Holochain.
    #[arg(long, default_value_t = Output::Log)]
    structured: Output,

    /// Force the admin port(s) that Holochain will use to a specific value.
    /// This option updates the conductor config file before starting Holochain
    /// and is only available with the `generate` and `run` commands.
    /// For example `hc sandbox -f=9000,9001 run`
    /// This must be set on each run or the port will change if it's in use.
    #[arg(short, long, value_delimiter = ',')]
    force_admin_ports: Vec<u16>,

    /// Set the path to the holochain binary.
    #[arg(
        short = 'H',
        long,
        env = "HC_HOLOCHAIN_PATH",
        default_value = "holochain"
    )]
    holochain_path: PathBuf,
}

/// The list of subcommands for `hc sandbox`.
#[derive(Debug, Parser)]
#[command(infer_subcommands = true)]
pub enum HcSandboxSubcommand {
    /// Generate one or more new Holochain Conductor sandbox(es) for later use.
    ///
    /// A single app will be installed as part of this sandbox.
    Generate {
        /// ID for the installed app.
        /// This is just a string to identify the app by.
        #[arg(short, long, default_value = DEFAULT_APP_ID)]
        app_id: InstalledAppId,

        /// (flattened)
        #[command(flatten)]
        create: Create,

        /// Automatically run the sandbox(es) that were created.
        /// This is effectively a combination of `hc sandbox generate` and `hc sandbox run`.
        /// You may optionally specify app interface ports to bind when running.
        /// This allows your UI to talk to the conductor.
        /// For example, `hc sandbox generate -r=0,9000,0` will create three app interfaces.
        /// Or, use `hc sandbox generate -r` to run without attaching any app interfaces.
        /// This follows the same structure as `hc sandbox run --ports`.
        #[arg(short, long, value_delimiter = ',')]
        run: Option<Vec<u16>>,

        /// A hApp bundle to install.
        happ: Option<PathBuf>,

        /// Network seed to use when installing the provided hApp.
        #[arg(long, short = 's')]
        network_seed: Option<String>,

        /// Optional path to a yaml file containing role settings to override
        /// the values in the dna manifest(s).
        /// See <https://github.com/holochain/holochain/tree/develop/crates/hc_sandbox/tests/fixtures/roles-settings.yaml>
        /// for an example of such a yaml file.
        #[arg(long)]
        roles_settings: Option<PathBuf>,
    },

    /// Run conductor(s) from existing sandbox(es).
    Run(Run),

    /// List sandboxes found in `$(pwd)/.hc`.
    List {
        /// Show more verbose information.
        #[arg(short, long, action = ArgAction::SetTrue)]
        verbose: bool,
    },

    /// Delete all sandboxes that are listed in the `$(pwd)/.hc` file and
    /// all files created by `hc sandbox` in `$(pwd)`.
    Clean,

    /// Delete specified sandboxes that are listed in the `$(pwd)/.hc` file.
    Remove {
        /// Remove a selection of existing conductor sandboxes
        /// from those specified in `$(pwd)/.hc`.
        /// Existing sandboxes and their indices are visible via `hc list`.
        /// Use the zero-based index to choose which sandboxes to use.
        /// For example `hc sandbox remove 1 3 5` or `hc remove run 1`
        #[arg(required = true, num_args = 1..)]
        indices: Vec<usize>,
    },

    /// Get admin ports from existing sandbox(es).
    ///
    /// This command outputs a JSON array of admin ports to stdout,
    /// which can be used with hc-client to connect to running conductors.
    AdminPorts {
        /// (flattened)
        #[command(flatten)]
        existing: Existing,
    },

    /// Create a fresh sandbox with no apps installed.
    Create(Create),
}

/// Options for running a sandbox
#[derive(Debug, Parser)]
pub struct Run {
    /// Optionally specifies app interface ports to bind when running.
    /// This allows your UI to talk to the conductor.
    /// For example, `hc -p=0,9000,0` will create three app interfaces.
    /// Important: Interfaces are persistent. If you add an interface
    /// it will be there next time you run the conductor.
    #[arg(short, long, value_delimiter = ',')]
    ports: Vec<u16>,

    /// (flattened)
    #[command(flatten)]
    existing: Existing,
}

impl HcSandbox {
    /// Run this command
    pub async fn run(self) -> anyhow::Result<()> {
        holochain_util::pw::pw_set_piped(self.piped);
        match self.subcommand {
            HcSandboxSubcommand::Generate {
                app_id,
                create,
                run,
                happ,
                network_seed,
                roles_settings,
            } => {
                let paths = generate(
                    &self.holochain_path,
                    happ,
                    create,
                    app_id,
                    network_seed,
                    roles_settings,
                    self.structured.clone(),
                )
                .await?;
                for (port, path) in self
                    .force_admin_ports
                    .clone()
                    .into_iter()
                    .zip(paths.clone().into_iter())
                {
                    crate::force_admin_port(path, port)?;
                }
                if let Some(ports) = run {
                    let holochain_path = self.holochain_path.clone();
                    let force_admin_ports = self.force_admin_ports.clone();
                    let structured = self.structured.clone();

                    let result = tokio::select! {
                        result = tokio::signal::ctrl_c() => {
                            msg!("Received Ctrl-C, shutting down");
                            result.map_err(anyhow::Error::from)
                        }
                        result = run_n(&holochain_path, paths, ports, force_admin_ports, structured) => result,
                    };
                    crate::save::release_ports(std::env::current_dir()?).await?;
                    return result;
                }
            }
            HcSandboxSubcommand::Run(Run { ports, existing }) => {
                let paths = existing.load(std::env::current_dir()?)?;
                if paths.is_empty() {
                    tracing::warn!("no paths available, exiting.");
                    return Ok(());
                }
                let holochain_path = self.holochain_path.clone();
                let force_admin_ports = self.force_admin_ports.clone();

                let result = tokio::select! {
                    result = tokio::signal::ctrl_c() => {
                        msg!("Received Ctrl-C, shutting down");
                        result.map_err(anyhow::Error::from)
                    }
                    result = run_n(&holochain_path, paths.into_iter().map(ConfigRootPath::from).collect(), ports, force_admin_ports, self.structured) => result,
                };
                crate::save::release_ports(std::env::current_dir()?).await?;
                return result;
            }
            HcSandboxSubcommand::List { verbose } => {
                crate::save::list(std::env::current_dir()?, verbose)?
            }
            HcSandboxSubcommand::Clean => {
                let removed_count = crate::save::remove(
                    std::env::current_dir()?,
                    Existing {
                        all: true,
                        indices: vec![],
                    },
                )?;
                match removed_count {
                    0 => msg!("No sandbox paths have been removed"),
                    1 => msg!("1 sandbox path has been removed"),
                    _ => msg!("{} sandbox paths have been removed", removed_count),
                }
            }
            HcSandboxSubcommand::Remove { indices } => {
                let removed_count = crate::save::remove(
                    std::env::current_dir()?,
                    Existing {
                        all: false,
                        indices,
                    },
                )?;
                match removed_count {
                    0 => msg!("No sandbox path has been removed"),
                    1 => msg!("1 sandbox path has been removed"),
                    _ => msg!("{} sandbox paths have been removed", removed_count),
                }
            }
            HcSandboxSubcommand::AdminPorts { existing } => {
                let paths = existing.load(std::env::current_dir()?)?;
                if paths.is_empty() {
                    println!("[]");
                    return Ok(());
                }
                let ports = crate::ports::get_admin_ports(paths).await?;
                println!("{}", serde_json::to_string(&ports)?);
            }
            HcSandboxSubcommand::Create(Create {
                num_sandboxes,
                network,
                root,
                directories,
                in_process_lair,
                #[cfg(feature = "chc")]
                chc_url,
            }) => {
                let mut paths = Vec::with_capacity(num_sandboxes.into());

                match num_sandboxes.into() {
                    1 => msg!("Creating 1 conductor sandbox"),
                    _ => msg!(
                        "Creating {} conductor sandboxes with same settings",
                        num_sandboxes
                    ),
                }

                for i in 0..num_sandboxes.into() {
                    let network = Network::to_kitsune(&NetworkCmd::as_inner(&network)).await;
                    let path = holochain_conductor_config::generate::generate(
                        network,
                        root.clone(),
                        directories.get(i).cloned(),
                        in_process_lair,
                        0,
                        #[cfg(feature = "chc")]
                        chc_url.clone(),
                    )?;
                    paths.push(path);
                }
                save_and_print(std::env::current_dir()?, paths)?;
            }
        }

        Ok(())
    }
}

/// Details about a conductor launched by the sandbox
#[derive(Debug, Serialize, Deserialize)]
pub struct LaunchInfo {
    /// The admin port that was bound. This is not known when admin ports are not forced because the
    /// default is 0 so the system will choose a port.
    pub admin_port: u16,
    /// The app ports that were attached to the conductor.
    pub app_ports: Vec<u16>,
}

impl LaunchInfo {
    pub(crate) fn from_admin_port(admin_port: u16) -> Self {
        LaunchInfo {
            admin_port,
            app_ports: vec![],
        }
    }
}

/// Run a conductor for each path
pub async fn run_n(
    holochain_path: &Path,
    paths: Vec<ConfigRootPath>,
    app_ports: Vec<u16>,
    force_admin_ports: Vec<u16>,
    structured: Output,
) -> anyhow::Result<()> {
    let run_holochain = |holochain_path: PathBuf,
                         path: ConfigRootPath,
                         index: usize,
                         ports,
                         force_admin_port,
                         structured| async move {
        crate::run::run(
            &holochain_path,
            path,
            index,
            ports,
            force_admin_port,
            structured,
        )
        .await?;
        Result::<_, anyhow::Error>::Ok(())
    };
    let mut force_admin_ports = force_admin_ports.into_iter();
    let mut app_ports = app_ports.into_iter();
    let jhs = paths
        .into_iter()
        .enumerate()
        .zip(std::iter::repeat_with(|| force_admin_ports.next()))
        .zip(std::iter::repeat_with(|| app_ports.next()))
        .map(|(((index, path), force_admin_port), app_port)| {
            let f = run_holochain(
                holochain_path.to_path_buf(),
                path,
                index,
                app_port.map(|p| vec![p]).unwrap_or_default(),
                force_admin_port,
                structured.clone(),
            );
            tokio::task::spawn(f)
        });
    futures::future::try_join_all(jhs).await?;
    Ok(())
}

/// Perform the `generate` subcommand
pub async fn generate(
    holochain_path: &Path,
    happ: Option<PathBuf>,
    create: Create,
    app_id: InstalledAppId,
    network_seed: Option<String>,
    roles_settings: Option<PathBuf>,
    structured: Output,
) -> anyhow::Result<Vec<ConfigRootPath>> {
    let happ = crate::bundles::parse_happ(happ)?;

    match create.num_sandboxes.into() {
        1 => msg!("Creating 1 conductor sandbox"),
        _ => msg!(
            "Creating {} conductor sandboxes with same settings",
            create.num_sandboxes
        ),
    }

    let paths = crate::sandbox::default_n(
        holochain_path,
        create,
        happ,
        app_id,
        network_seed,
        roles_settings,
        structured,
    )
    .await?;
    save_and_print(std::env::current_dir()?, paths.clone())?;
    Ok(paths)
}

fn save_and_print(hc_dir: PathBuf, paths: Vec<ConfigRootPath>) -> std::io::Result<()> {
    let pre_existing = crate::save::load(hc_dir.clone())?;
    crate::save::save(hc_dir, paths.clone())?;
    match paths.len() {
        1 => msg!(
            "Created 1 sandbox:\n{}:{}",
            pre_existing.len(),
            paths[0].display()
        ),
        _ => {
            msg!("Created {} sandboxes:", paths.len());
            for (i, path) in paths.into_iter().enumerate() {
                msg!("{}:{}", pre_existing.len() + i, path.display());
            }
        }
    }
    Ok(())
}