canic-host 0.111.0

Host-side App build and desired-state Fleet reconciliation library for Canic workspaces
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
//! Module: canister_protocol
//!
//! Responsibility: invoke typed Canic Candid methods through ICP-selected transports.
//! Does not own: domain sequencing, endpoint authorization, or management-Canister effects.
//! Boundary: domain workflows supply exact Canister, method, and arguments through explicit
//! query or update operations.

pub mod contract;
pub mod inspection;

use crate::{
    icp::{
        IcpCli, IcpCommandError, IcpJsonResponseError, cleanup_candid_argument_file,
        decode_json_result_response, write_candid_argument_file,
    },
    protocol_binding::ResolvedProtocolBinding,
};
use candid::{CandidType, Principal};
use canic_contracts::diagnostics::RegisteredDiagnosticCode;
use serde::de::DeserializeOwned;
use std::io;
use thiserror::Error as ThisError;

const ICP_JSON_OUTPUT: &str = "json";

#[derive(Clone, Copy)]
enum ProtocolCallMode {
    Query,
    Update,
}

#[derive(Debug, ThisError)]
pub enum CanisterProtocolError {
    #[error("read-only query {method} on Canister {canister} failed: {source}")]
    ReadOnlyQuery {
        canister: Principal,
        method: &'static str,
        #[source]
        source: crate::icp::IcpQueryError,
    },

    #[error("invalid bound inspection contract for Root {caller}: {detail}")]
    InspectionContract { caller: Principal, detail: String },

    #[error("Root {} inspection preflight for {} observed native={} cycles, liquid={} cycles, required outbound reserve={} cycles. Inspection was not attempted. Review Root funding or freezing reserve and retry with a fresh observation.", .0.caller, .0.canister_id, .0.native_cycles, .0.available_liquid_cycles, .0.required_liquid_cycles)]
    InspectionPreflightReserve(
        Box<canic_contracts::dto::canister::CanisterInspectionReserveResponse>,
    ),

    #[error("{}: Root {} cannot inspect {}: native={} cycles, liquid={} cycles, required outbound reserve={} cycles. Review Root funding or freezing reserve before retrying.", canic_contracts::diagnostics::codes::PLATFORM_INSUFFICIENT_LIQUID_CYCLES, .0.caller, .0.canister_id, .0.native_cycles, .0.available_liquid_cycles, .0.required_liquid_cycles)]
    InspectionReserve(Box<canic_contracts::dto::canister::CanisterInspectionReserveResponse>),

    #[error("Root {caller} returned invalid reserve evidence for inspection of {target}")]
    InvalidInspectionReserve {
        caller: Principal,
        target: Principal,
    },

    #[error("failed to encode Candid arguments for {method} on Canister {canister}: {source}")]
    ArgumentEncoding {
        canister: Principal,
        method: &'static str,
        #[source]
        source: candid::Error,
    },

    #[error(
        "failed to manage binary Candid arguments for {method} on Canister {canister}: {source}"
    )]
    ArgumentFile {
        canister: Principal,
        method: &'static str,
        #[source]
        source: io::Error,
    },

    #[error("failed to invoke {method} on Canister {canister}: {source}")]
    Invocation {
        canister: Principal,
        method: &'static str,
        #[source]
        source: IcpCommandError,
    },

    #[error("invalid {method} response from Canister {canister}: {source}")]
    Response {
        canister: Principal,
        method: &'static str,
        #[source]
        source: IcpJsonResponseError,
    },
}

impl CanisterProtocolError {
    pub(crate) fn inspection_reserve(
        caller: Principal,
        target: Principal,
        evidence: canic_contracts::dto::canister::CanisterInspectionReserveResponse,
    ) -> Self {
        if evidence.caller != caller
            || evidence.canister_id != target
            || evidence.available_liquid_cycles >= evidence.required_liquid_cycles
            || evidence.available_liquid_cycles > evidence.native_cycles
        {
            return Self::InvalidInspectionReserve { caller, target };
        }
        Self::InspectionReserve(Box::new(evidence))
    }

    pub(crate) fn is_rejected_with(&self, code: RegisteredDiagnosticCode) -> bool {
        if matches!(self, Self::InspectionReserve(_)) {
            return code
                == canic_contracts::diagnostics::codes::PLATFORM_INSUFFICIENT_LIQUID_CYCLES;
        }
        matches!(
            self,
            Self::Response {
                source: IcpJsonResponseError::Rejected(error),
                ..
            } if error.code() == code.raw_code()
        )
    }
}

pub fn call_with_arg<I, O>(
    icp: &IcpCli,
    binding: &ResolvedProtocolBinding,
    canister: Principal,
    method: &'static str,
    input: &I,
) -> Result<O, CanisterProtocolError>
where
    I: CandidType,
    O: CandidType + DeserializeOwned,
{
    invoke_with_candid(
        icp,
        &binding.candid_path,
        canister,
        method,
        input,
        ProtocolCallMode::Update,
    )
}

pub fn query_with_arg<I, O>(
    icp: &IcpCli,
    binding: &ResolvedProtocolBinding,
    canister: Principal,
    method: &'static str,
    input: &I,
) -> Result<O, CanisterProtocolError>
where
    I: CandidType,
    O: CandidType + DeserializeOwned,
{
    invoke_with_candid(
        icp,
        &binding.candid_path,
        canister,
        method,
        input,
        ProtocolCallMode::Query,
    )
}

/// Invoke one typed current-generation call after its exact Candid bytes were
/// independently bound into the reviewed Fleet action.
pub fn call_with_candid<I, O>(
    icp: &IcpCli,
    candid_path: &std::path::Path,
    canister: Principal,
    method: &'static str,
    input: &I,
) -> Result<O, CanisterProtocolError>
where
    I: CandidType,
    O: CandidType + DeserializeOwned,
{
    invoke_with_candid(
        icp,
        candid_path,
        canister,
        method,
        input,
        ProtocolCallMode::Update,
    )
}

/// Query one typed current-generation status after its exact Candid bytes were
/// independently bound into the reviewed Fleet action.
pub fn query_with_candid<I, O>(
    icp: &IcpCli,
    candid_path: &std::path::Path,
    canister: Principal,
    method: &'static str,
    input: &I,
) -> Result<O, CanisterProtocolError>
where
    I: CandidType,
    O: CandidType + DeserializeOwned,
{
    invoke_with_candid(
        icp,
        candid_path,
        canister,
        method,
        input,
        ProtocolCallMode::Query,
    )
}

/// Read a compiled Canic status contract while preserving typed transport failures.
pub fn query_authenticated<I: CandidType, O: CandidType + DeserializeOwned>(
    icp: &IcpCli,
    canister: Principal,
    method: &'static str,
    input: &I,
) -> Result<O, CanisterProtocolError> {
    let response: Result<O, canic_contracts::dto::error::Error> = icp
        .query_candid_readonly(canister, method, input)
        .map_err(|source| CanisterProtocolError::ReadOnlyQuery {
            canister,
            method,
            source,
        })?;
    response.map_err(|error| CanisterProtocolError::Response {
        canister,
        method,
        source: IcpJsonResponseError::Rejected(error),
    })
}

fn invoke_with_candid<I, O>(
    icp: &IcpCli,
    candid_path: &std::path::Path,
    canister: Principal,
    method: &'static str,
    input: &I,
    mode: ProtocolCallMode,
) -> Result<O, CanisterProtocolError>
where
    I: CandidType,
    O: CandidType + DeserializeOwned,
{
    let output = invoke_output(icp, Some(candid_path), canister, method, input, mode)?;
    decode_response(canister, method, &output)
}

fn invoke_output<I>(
    icp: &IcpCli,
    candid_path: Option<&std::path::Path>,
    canister: Principal,
    method: &'static str,
    input: &I,
    mode: ProtocolCallMode,
) -> Result<String, CanisterProtocolError>
where
    I: CandidType,
{
    let bytes =
        candid::encode_one(input).map_err(|source| CanisterProtocolError::ArgumentEncoding {
            canister,
            method,
            source,
        })?;
    let args_path = write_candid_argument_file(&bytes).map_err(|source| {
        CanisterProtocolError::ArgumentFile {
            canister,
            method,
            source,
        }
    })?;
    let canister_text = canister.to_text();
    let output = match mode {
        ProtocolCallMode::Query => icp.canister_query_binary_args_output_with_candid(
            &canister_text,
            method,
            &args_path,
            Some(ICP_JSON_OUTPUT),
            candid_path,
        ),
        ProtocolCallMode::Update => icp.canister_call_binary_args_output_with_candid(
            &canister_text,
            method,
            &args_path,
            Some(ICP_JSON_OUTPUT),
            candid_path,
        ),
    };
    cleanup_candid_argument_file(&args_path);
    let output = output.map_err(|source| CanisterProtocolError::Invocation {
        canister,
        method,
        source,
    })?;
    Ok(output)
}

fn decode_response<O>(
    canister: Principal,
    method: &'static str,
    output: &str,
) -> Result<O, CanisterProtocolError>
where
    O: CandidType + DeserializeOwned,
{
    decode_json_result_response(output).map_err(|source| CanisterProtocolError::Response {
        canister,
        method,
        source,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::Deserialize;
    use std::fs;

    #[derive(CandidType, Debug, Deserialize, Eq, PartialEq)]
    struct EmptyVectorArgument {
        values: Vec<u64>,
    }

    #[cfg(unix)]
    #[test]
    fn cleanup_failure_preserves_typed_update_and_query_outcomes() {
        use canic_core::cdk::utils::hash::hex_bytes;
        use std::{os::unix::fs::PermissionsExt, path::PathBuf};

        let root = crate::test_support::temp_dir("canister-protocol-cleanup");
        fs::create_dir_all(&root).unwrap();
        let executable = root.join("icp");
        fs::write(
            &executable,
            crate::test_support::tool_script(
                r#"#!/bin/sh
if [ "$1" = --version ]; then echo 'icp @ICP_VERSION@'; exit 0; fi
while [ "$#" -gt 0 ]; do
  case "$1" in --args-file) shift; argument=$1 ;; esac
  shift
done
printf '%s\n' "$argument" > argument-path
rm "$argument"; mkdir "$argument"
cat response
exit "$(cat exit-code)"
"#,
            ),
        )
        .unwrap();
        fs::set_permissions(&executable, fs::Permissions::from_mode(0o700)).unwrap();
        let icp = IcpCli::new(executable.to_str().unwrap(), None).with_cwd(&root);
        let reply: Result<u64, canic_contracts::dto::error::Error> = Ok(42);
        let response = serde_json::json!({
            "response_bytes": hex_bytes(candid::encode_one(reply).unwrap()),
        });
        for mode in [ProtocolCallMode::Update, ProtocolCallMode::Query] {
            for outcome in 0..3 {
                fs::write(root.join("exit-code"), if outcome == 1 { "1" } else { "0" }).unwrap();
                fs::write(
                    root.join("response"),
                    if outcome == 2 {
                        "{}".to_string()
                    } else {
                        response.to_string()
                    },
                )
                .unwrap();
                let result = invoke_with_candid::<_, u64>(
                    &icp,
                    &root.join("probe.did"),
                    Principal::from_slice(&[1]),
                    "probe",
                    &(),
                    mode,
                );
                match outcome {
                    0 => assert_eq!(result.unwrap(), 42),
                    1 => assert!(matches!(
                        result,
                        Err(CanisterProtocolError::Invocation { .. })
                    )),
                    _ => assert!(matches!(
                        result,
                        Err(CanisterProtocolError::Response { .. })
                    )),
                }
                let argument_path = PathBuf::from(
                    fs::read_to_string(root.join("argument-path"))
                        .unwrap()
                        .trim(),
                );
                assert!(argument_path.is_dir());
                fs::remove_dir(argument_path).unwrap();
            }
        }
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn inspection_reserve_requires_exact_authority_and_retains_numeric_cause() {
        use canic_contracts::{
            diagnostics::codes, dto::canister::CanisterInspectionReserveResponse,
        };
        let root = Principal::from_slice(&[1]);
        let target = Principal::from_slice(&[2]);
        let evidence = CanisterInspectionReserveResponse {
            caller: root,
            canister_id: target,
            native_cycles: 1000,
            available_liquid_cycles: 50,
            required_liquid_cycles: 100,
        };
        let error = CanisterProtocolError::inspection_reserve(root, target, evidence.clone());
        assert!(error.is_rejected_with(codes::PLATFORM_INSUFFICIENT_LIQUID_CYCLES));
        assert!(!error.is_rejected_with(codes::PLATFORM_UNAVAILABLE));
        let CanisterProtocolError::InspectionReserve(actual) = &error else {
            panic!("reserve evidence");
        };
        assert_eq!(**actual, evidence);
        assert!(error.to_string().contains(
            "native=1000 cycles, liquid=50 cycles, required outbound reserve=100 cycles"
        ));
        for invalid in [
            CanisterInspectionReserveResponse {
                caller: target,
                ..evidence.clone()
            },
            CanisterInspectionReserveResponse {
                canister_id: root,
                ..evidence.clone()
            },
            CanisterInspectionReserveResponse {
                available_liquid_cycles: 100,
                ..evidence.clone()
            },
            CanisterInspectionReserveResponse {
                native_cycles: 49,
                ..evidence
            },
        ] {
            let error = CanisterProtocolError::inspection_reserve(root, target, invalid);
            assert!(matches!(
                error,
                CanisterProtocolError::InvalidInspectionReserve { .. }
            ));
            assert!(!error.is_rejected_with(codes::PLATFORM_INSUFFICIENT_LIQUID_CYCLES));
        }
    }

    #[test]
    fn typed_arguments_are_written_to_private_binary_files() {
        let argument = EmptyVectorArgument { values: Vec::new() };
        let path =
            write_candid_argument_file(&candid::encode_one(&argument).expect("encode argument"))
                .expect("write argument file");

        let decoded: EmptyVectorArgument =
            candid::decode_one(&fs::read(&path).expect("read argument file"))
                .expect("decode argument");
        assert_eq!(decoded, argument);
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;

            assert_eq!(
                fs::metadata(&path)
                    .expect("argument metadata")
                    .permissions()
                    .mode()
                    & 0o777,
                0o600
            );
        }
        fs::remove_file(path).expect("remove argument file");
    }
}