canic-cli 0.33.5

Operator CLI for Canic fleet backup and restore workflows
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
use crate::{
    args::{default_icp, flag_arg, local_network, parse_matches, print_help_or_version, value_arg},
    version_text,
};
use canic_host::{icp::IcpCli, release_set::icp_root};
use clap::Command as ClapCommand;
use serde::Serialize;
use std::{
    ffi::OsString,
    fs,
    path::{Path, PathBuf},
};
use thiserror::Error as ThisError;

const CANDID_SERVICE_METADATA: &str = "candid:service";
const HELP_AFTER: &str = "\
Examples:
  canic endpoints app
  canic endpoints app --environment demo
  canic endpoints tl4x7-vh777-77776-aaacq-cai --role app --environment demo";

///
/// EndpointsCommandError
///

#[derive(Debug, ThisError)]
pub enum EndpointsCommandError {
    #[error("{0}")]
    Usage(String),

    #[error("canister interface did not contain a service block")]
    MissingService,

    #[error(
        "live metadata was unavailable for {canister} and no local Candid artifact could be resolved; pass a canister role with `--role <role>` or a Candid file with `--did <path>`"
    )]
    NoInterfaceArtifact { canister: String },

    #[error("local Candid artifact not found for role {role}; looked under {root}")]
    MissingRoleArtifact { role: String, root: String },

    #[error("failed to read local Candid artifact {path}: {source}")]
    ReadDid {
        path: String,
        source: std::io::Error,
    },

    #[error("failed to render endpoint output: {0}")]
    Json(#[from] serde_json::Error),
}

///
/// EndpointsOptions
///

#[derive(Clone, Debug, Eq, PartialEq)]
struct EndpointsOptions {
    canister: String,
    role: Option<String>,
    did: Option<PathBuf>,
    environment: Option<String>,
    network: Option<String>,
    icp: String,
    json: bool,
}

impl EndpointsOptions {
    fn parse<I>(args: I) -> Result<Self, EndpointsCommandError>
    where
        I: IntoIterator<Item = OsString>,
    {
        let matches =
            parse_matches(command(), args).map_err(|_| EndpointsCommandError::Usage(usage()))?;
        Ok(Self {
            canister: string_value(&matches, "canister").expect("clap requires canister"),
            role: string_value(&matches, "role"),
            did: string_value(&matches, "did").map(PathBuf::from),
            environment: string_value(&matches, "environment"),
            network: string_value(&matches, "network"),
            icp: string_value(&matches, "icp").unwrap_or_else(default_icp),
            json: matches.get_flag("json"),
        })
    }

    fn artifact_role(&self) -> Option<&str> {
        self.role.as_deref().or_else(|| {
            if is_principal_like(&self.canister) {
                None
            } else {
                Some(self.canister.as_str())
            }
        })
    }
}

///
/// EndpointReport
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
struct EndpointReport {
    source: String,
    endpoints: Vec<String>,
}

/// Run the canister endpoint listing command.
pub fn run<I>(args: I) -> Result<(), EndpointsCommandError>
where
    I: IntoIterator<Item = OsString>,
{
    let args = args.into_iter().collect::<Vec<_>>();
    if print_help_or_version(&args, usage, version_text()) {
        return Ok(());
    }

    let options = EndpointsOptions::parse(args)?;
    let report = endpoint_report(&options)?;
    if options.json {
        println!("{}", serde_json::to_string_pretty(&report)?);
    } else {
        println!("{}", report.endpoints.join("\n"));
    }
    Ok(())
}

fn endpoint_report(options: &EndpointsOptions) -> Result<EndpointReport, EndpointsCommandError> {
    if let Some(path) = &options.did {
        let candid = read_did(path)?;
        return Ok(EndpointReport {
            source: path.display().to_string(),
            endpoints: parse_candid_service_methods(&candid)?,
        });
    }

    if let Ok(candid) = read_live_candid(options) {
        return Ok(EndpointReport {
            source: format!("{} metadata", options.canister),
            endpoints: parse_candid_service_methods(&candid)?,
        });
    }

    let Some(role) = options.artifact_role() else {
        return Err(EndpointsCommandError::NoInterfaceArtifact {
            canister: options.canister.clone(),
        });
    };
    let path = resolve_role_did(options, role)?;
    let candid = read_did(&path)?;
    Ok(EndpointReport {
        source: path.display().to_string(),
        endpoints: parse_candid_service_methods(&candid)?,
    })
}

fn read_live_candid(
    options: &EndpointsOptions,
) -> Result<String, canic_host::icp::IcpCommandError> {
    IcpCli::new(
        &options.icp,
        options.environment.clone(),
        options.network.clone(),
    )
    .canister_metadata_output(&options.canister, CANDID_SERVICE_METADATA)
}

fn resolve_role_did(
    options: &EndpointsOptions,
    role: &str,
) -> Result<PathBuf, EndpointsCommandError> {
    let root = icp_root().unwrap_or_else(|_| PathBuf::from("."));
    for network in artifact_network_candidates(options) {
        let path = root
            .join(".icp")
            .join(&network)
            .join("canisters")
            .join(role)
            .join(format!("{role}.did"));
        if path.is_file() {
            return Ok(path);
        }
    }

    Err(EndpointsCommandError::MissingRoleArtifact {
        role: role.to_string(),
        root: root.display().to_string(),
    })
}

fn artifact_network_candidates(options: &EndpointsOptions) -> Vec<String> {
    let mut networks = Vec::new();
    if let Some(network) = &options.network {
        networks.push(network.clone());
    }
    if let Some(environment) = &options.environment {
        networks.push(environment.clone());
    }
    networks.push(local_network());
    networks.sort();
    networks.dedup();
    networks
}

fn read_did(path: &Path) -> Result<String, EndpointsCommandError> {
    fs::read_to_string(path).map_err(|source| EndpointsCommandError::ReadDid {
        path: path.display().to_string(),
        source,
    })
}

fn parse_candid_service_methods(candid: &str) -> Result<Vec<String>, EndpointsCommandError> {
    let Some(service_start) = find_service_body_start(candid) else {
        return Err(EndpointsCommandError::MissingService);
    };

    let mut methods = Vec::new();
    let mut depth = 0usize;
    let mut at_line_start = true;
    let mut chars = candid[service_start..].char_indices().peekable();
    while let Some((_, ch)) = chars.next() {
        match ch {
            '{' => {
                depth += 1;
                at_line_start = false;
            }
            '}' => {
                if depth == 0 {
                    break;
                }
                depth -= 1;
                at_line_start = false;
                if depth == 0 {
                    break;
                }
            }
            '\n' => {
                at_line_start = true;
            }
            _ if depth == 1 && at_line_start && !ch.is_whitespace() => {
                let rest = remaining_line(candid, service_start, ch, &mut chars);
                if let Some(method) = parse_service_method_line(&rest) {
                    methods.push(method);
                }
                at_line_start = true;
            }
            _ if depth == 1 && at_line_start && ch.is_whitespace() => {}
            _ => {
                at_line_start = false;
            }
        }
    }

    Ok(methods)
}

fn find_service_body_start(candid: &str) -> Option<usize> {
    let mut search_from = 0usize;
    while let Some(offset) = candid[search_from..].find("service") {
        let service_index = search_from + offset;
        if !is_word_boundary(candid, service_index, "service") {
            search_from = service_index + "service".len();
            continue;
        }
        let service_tail = &candid[service_index..];
        let body_search_start = service_tail
            .find("->")
            .map_or(service_index, |offset| service_index + offset + "->".len());
        let brace_offset = candid[body_search_start..].find('{')?;
        return Some(body_search_start + brace_offset);
    }
    None
}

fn is_word_boundary(text: &str, index: usize, word: &str) -> bool {
    let before = text[..index].chars().next_back();
    let after = text[index + word.len()..].chars().next();
    before.is_none_or(|ch| !is_identifier_char(ch))
        && after.is_none_or(|ch| !is_identifier_char(ch))
}

const fn is_identifier_char(ch: char) -> bool {
    ch.is_ascii_alphanumeric() || ch == '_'
}

fn remaining_line(
    candid: &str,
    service_start: usize,
    first: char,
    chars: &mut std::iter::Peekable<std::str::CharIndices<'_>>,
) -> String {
    let mut line = first.to_string();
    while let Some((index, ch)) = chars.peek().copied() {
        if ch == '\n' {
            break;
        }
        chars.next();
        let absolute = service_start + index;
        if candid.is_char_boundary(absolute) {
            line.push(ch);
        }
    }
    line
}

fn parse_service_method_line(line: &str) -> Option<String> {
    let trimmed = line.trim_start();
    if trimmed.starts_with("//") || trimmed.starts_with('}') {
        return None;
    }
    if let Some(stripped) = trimmed.strip_prefix('"') {
        let end = stripped.find('"')?;
        let name = &stripped[..end];
        let after = stripped[end + 1..].trim_start();
        return after.starts_with(':').then(|| name.to_string());
    }
    let end = trimmed
        .char_indices()
        .find_map(|(index, ch)| (ch.is_whitespace() || ch == ':').then_some(index))?;
    let name = &trimmed[..end];
    let after = trimmed[end..].trim_start();
    (!name.is_empty() && after.starts_with(':')).then(|| name.to_string())
}

fn is_principal_like(value: &str) -> bool {
    value.contains('-')
        && value
            .chars()
            .all(|ch| ch.is_ascii_alphanumeric() || ch == '-')
}

fn string_value(matches: &clap::ArgMatches, id: &str) -> Option<String> {
    matches.try_get_one::<String>(id).ok().flatten().cloned()
}

fn command() -> ClapCommand {
    ClapCommand::new("endpoints")
        .bin_name("canic endpoints")
        .disable_help_flag(true)
        .about("List callable methods exposed by a canister Candid interface")
        .arg(
            value_arg("canister")
                .value_name("canister-or-role")
                .required(true)
                .help("Canister name, principal, or local role name to inspect"),
        )
        .arg(
            value_arg("role")
                .long("role")
                .value_name("role")
                .help("Local canister role to use for artifact fallback"),
        )
        .arg(
            value_arg("did")
                .long("did")
                .value_name("path")
                .help("Read endpoints from a specific Candid file"),
        )
        .arg(
            value_arg("environment")
                .long("environment")
                .short('e')
                .value_name("name")
                .help("ICP CLI environment for live metadata lookup"),
        )
        .arg(
            value_arg("network")
                .long("network")
                .value_name("name")
                .help("ICP CLI network for live metadata lookup"),
        )
        .arg(
            value_arg("icp")
                .long("icp")
                .value_name("path")
                .help("Path to the icp executable"),
        )
        .arg(flag_arg("json").long("json").help("Print JSON output"))
        .after_help(HELP_AFTER)
}

fn usage() -> String {
    let mut command = command();
    command.render_help().to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    const CANDID: &str = r#"
type Nested = record { field : text };
service : (record { init : text }) -> {
  canic_ready : () -> (bool) query;
  "icrc10-supported-standards" : () -> (vec record { text; text }) query;
  canic_update : (Nested) -> (
      variant { Ok; Err : text },
    );
}
"#;

    // Ensure generated Candid service files can be reduced to endpoint names.
    #[test]
    fn parses_candid_service_methods() {
        let methods = super::parse_candid_service_methods(CANDID).expect("parse methods");

        assert_eq!(
            methods,
            vec!["canic_ready", "icrc10-supported-standards", "canic_update"]
        );
    }

    // Ensure principal arguments require an explicit role for local artifact fallback.
    #[test]
    fn principal_arguments_do_not_guess_role() {
        let options = EndpointsOptions {
            canister: "tl4x7-vh777-77776-aaacq-cai".to_string(),
            role: None,
            did: None,
            environment: Some("demo".to_string()),
            network: None,
            icp: "icp".to_string(),
            json: false,
        };

        assert_eq!(options.artifact_role(), None);
    }

    // Ensure endpoint options parse local and live lookup controls.
    #[test]
    fn parses_endpoint_options() {
        let options = EndpointsOptions::parse([
            OsString::from("app"),
            OsString::from("--environment"),
            OsString::from("demo"),
            OsString::from("--network"),
            OsString::from("local"),
            OsString::from("--role"),
            OsString::from("app"),
            OsString::from("--icp"),
            OsString::from("/bin/icp"),
            OsString::from("--json"),
        ])
        .expect("parse options");

        assert_eq!(options.canister, "app");
        assert_eq!(options.environment.as_deref(), Some("demo"));
        assert_eq!(options.network.as_deref(), Some("local"));
        assert_eq!(options.role.as_deref(), Some("app"));
        assert_eq!(options.icp, "/bin/icp");
        assert!(options.json);
    }
}