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
//! Definitions of Parser options for use in the CLI

use crate::cmds::*;
use clap::{ArgAction, Parser};
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 hc uses to talk to Holochain to a specific value.
    /// 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>,
    },

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

    /// Make a call to a conductor's admin interface.
    Call(crate::calls::Call),

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

    /// Clean (completely remove) sandboxes that are listed in the `$(pwd)/.hc` file.
    Clean,

    /// 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,
            } => {
                let paths = generate(
                    &self.holochain_path,
                    happ,
                    create,
                    app_id,
                    network_seed,
                    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() => 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()?;
                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() => result.map_err(anyhow::Error::from),
                    result = run_n(&holochain_path, paths, ports, force_admin_ports, self.structured) => result,
                };
                crate::save::release_ports(std::env::current_dir()?).await?;
                return result;
            }
            HcSandboxSubcommand::Call(call) => {
                crate::calls::call(&self.holochain_path, call, self.structured).await?
            }
            // HcSandboxSubcommand::Task => todo!("Running custom tasks is coming soon"),
            HcSandboxSubcommand::List { verbose } => {
                crate::save::list(std::env::current_dir()?, verbose)?
            }
            HcSandboxSubcommand::Clean => crate::save::clean(std::env::current_dir()?, Vec::new())?,
            HcSandboxSubcommand::Create(Create {
                num_sandboxes,
                network,
                root,
                directories,
                in_process_lair,
            }) => {
                let mut paths = Vec::with_capacity(num_sandboxes);
                msg!(
                    "Creating {} conductor sandboxes with same settings",
                    num_sandboxes
                );
                for i in 0..num_sandboxes {
                    let path = crate::generate::generate(
                        network.clone().map(|n| n.into_inner().into()),
                        root.clone(),
                        directories.get(i).cloned(),
                        in_process_lair,
                    )?;
                    paths.push(path);
                }
                crate::save::save(std::env::current_dir()?, paths.clone())?;
                msg!("Created {:?}", 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![],
        }
    }
}

pub async fn run_n(
    holochain_path: &Path,
    paths: Vec<PathBuf>,
    app_ports: Vec<u16>,
    force_admin_ports: Vec<u16>,
    structured: Output,
) -> anyhow::Result<()> {
    let run_holochain = |holochain_path: PathBuf,
                         path: PathBuf,
                         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(())
}

pub async fn generate(
    holochain_path: &Path,
    happ: Option<PathBuf>,
    create: Create,
    app_id: InstalledAppId,
    network_seed: Option<String>,
    structured: Output,
) -> anyhow::Result<Vec<PathBuf>> {
    let happ = crate::bundles::parse_happ(happ)?;
    let paths = crate::sandbox::default_n(
        holochain_path,
        create,
        happ,
        app_id,
        network_seed,
        structured,
    )
    .await?;
    crate::save::save(std::env::current_dir()?, paths.clone())?;
    Ok(paths)
}