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
use std::{
    env,
    ffi::OsStr,
    io,
    os::fd::BorrowedFd,
    path::{Path, PathBuf},
    process::Command,
};

#[cfg(unix)]
use std::os::unix::process::CommandExt;

#[cfg(unix)]
use rustix::io::{FdFlags, fcntl_getfd, fcntl_setfd};

use crate::release_set::artifact_root_path;

use super::{
    error::IcpCommandError,
    model::{IcpCli, LOCAL_ICP_TARGET, LocalReplicaTarget},
    version::compatible_version_output,
};

/// Optional absolute path relayed to every ICP CLI subprocess for an encrypted identity.
pub const CANIC_ICP_IDENTITY_PASSWORD_FILE_ENV: &str = "CANIC_ICP_IDENTITY_PASSWORD_FILE";

const REQUEST_RUNTIME_WORKERS_ENV: &str = "TOKIO_WORKER_THREADS";

impl IcpCli {
    /// Build an ICP CLI command context from an executable path and optional ICP environment.
    #[must_use]
    pub fn new(executable: impl Into<String>, environment: Option<String>) -> Self {
        Self {
            timing: std::sync::Arc::default(),
            identity_lookup_millis: std::sync::Arc::default(),
            identity_lookups: std::sync::Arc::default(),
            remote_calls: std::sync::Arc::default(),
            executable: executable.into(),
            environment,
            cwd: None,
            local_replica: None,
            inherited_fd: None,
            identity_password_file: configured_identity_password_file(),
            selected_identity: std::sync::Arc::default(),
            compatible_version: std::sync::Arc::default(),
            query_transport: std::sync::Arc::default(),
        }
    }

    /// Count logical remote transport attempts, including failures, across this context's clones.
    /// Replica handshakes and local CLI metadata discovery are excluded.
    #[must_use]
    pub(crate) fn remote_call_count(&self) -> u64 {
        self.remote_calls.load(std::sync::atomic::Ordering::Relaxed)
    }

    /// Local Principal resolution attempts, shared across transport clones.
    pub(crate) fn identity_lookup_count(&self) -> u64 {
        self.identity_lookups
            .load(std::sync::atomic::Ordering::Relaxed)
    }

    pub(crate) fn identity_lookup_millis(&self) -> u64 {
        self.identity_lookup_millis
            .load(std::sync::atomic::Ordering::Relaxed)
    }

    pub(crate) fn record_remote_call(&self) {
        self.remote_calls
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }

    /// Return a copy of this ICP CLI context rooted at one project directory.
    #[must_use]
    pub fn with_cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
        let cwd = Some(cwd.into());
        if self.cwd != cwd {
            self.compatible_version = std::sync::Arc::default();
        }
        self.cwd = cwd;
        self
    }

    /// Return a copy using an explicit direct local replica target.
    #[must_use]
    pub fn with_local_replica(mut self, target: Option<LocalReplicaTarget>) -> Self {
        self.local_replica = target;
        self
    }

    /// Keep one caller-owned descriptor open in commands spawned by this context.
    #[must_use]
    pub const fn with_inherited_fd(mut self, inherited_fd: Option<i32>) -> Self {
        self.inherited_fd = inherited_fd;
        self
    }

    /// Relay one explicit password file to every ICP CLI subprocess.
    #[must_use]
    pub fn with_identity_password_file(mut self, path: impl Into<PathBuf>) -> Self {
        self.identity_password_file = Some(path.into());
        self
    }

    /// Select an identity for this context without reading or changing ICP's default.
    /// Clones retain the selection; the caller still verifies its expected Principal.
    #[must_use]
    pub fn with_identity(mut self, identity: Option<&str>) -> Self {
        if let Some(identity) = identity {
            self.selected_identity =
                std::sync::Arc::new(std::sync::OnceLock::from(identity.to_owned()));
        }
        self
    }

    /// Return the optional ICP environment carried by this command context.
    #[must_use]
    pub fn environment(&self) -> Option<&str> {
        self.environment.as_deref()
    }

    /// Build a base ICP CLI command from this context.
    #[must_use]
    pub fn command(&self) -> Command {
        let mut command = Command::new(&self.executable);
        add_identity_password_file_arg(&mut command, self.identity_password_file.as_deref());
        if let Some(cwd) = &self.cwd {
            command.current_dir(cwd);
            add_project_root_override_arg(&mut command, cwd);
        }
        configure_inherited_fd(&mut command, self.inherited_fd);
        command
    }

    /// Build a base ICP CLI command rooted at one workspace directory.
    #[must_use]
    pub fn command_in(&self, cwd: &Path) -> Command {
        let mut command = Command::new(&self.executable);
        add_identity_password_file_arg(&mut command, self.identity_password_file.as_deref());
        command.current_dir(cwd);
        add_project_root_override_arg(&mut command, cwd);
        configure_inherited_fd(&mut command, self.inherited_fd);
        command
    }

    /// Build an `icp canister ...` command with optional environment selection applied.
    #[must_use]
    pub fn canister_command(&self) -> Command {
        let mut command = self.request_command();
        command.arg("canister");
        command
    }

    /// Bound startup work for a short-lived request without changing replica commands.
    pub(super) fn request_command(&self) -> Command {
        let mut command = self.command();
        configure_request_runtime(
            &mut command,
            env::var_os(REQUEST_RUNTIME_WORKERS_ENV).as_deref(),
        );
        command
    }

    pub(crate) fn add_target_args(&self, command: &mut Command) {
        self.add_selected_identity_arg(command);
        add_target_args(command, self.environment(), self.local_replica.as_ref());
    }

    pub(super) fn add_selected_identity_arg(&self, command: &mut Command) {
        if let Some(identity) = self.selected_identity.get() {
            command.arg("--identity").arg(identity);
        }
    }
}

fn configure_request_runtime(command: &mut Command, inherited: Option<&OsStr>) {
    if inherited.is_none()
        && !command
            .get_envs()
            .any(|(key, _)| key == REQUEST_RUNTIME_WORKERS_ENV)
    {
        // One request needs I/O progress, not one worker per host CPU. Keep a second
        // worker for background tasks; explicit operator/command settings take precedence.
        command.env(REQUEST_RUNTIME_WORKERS_ENV, "2");
    }
}

fn configured_identity_password_file() -> Option<PathBuf> {
    env::var_os(CANIC_ICP_IDENTITY_PASSWORD_FILE_ENV)
        .filter(|path| !path.is_empty())
        .map(PathBuf::from)
}

fn add_identity_password_file_arg(command: &mut Command, path: Option<&Path>) {
    if let Some(path) = path {
        command.arg("--identity-password-file").arg(path);
    }
}

pub(super) fn configure_inherited_fd(command: &mut Command, inherited_fd: Option<i32>) {
    let Some(inherited_fd) = inherited_fd else {
        return;
    };

    #[cfg(unix)]
    // SAFETY: the closure performs only fcntl operations on the caller-owned
    // descriptor between fork and exec. The caller keeps that descriptor open
    // until the synchronous command completes.
    unsafe {
        command.pre_exec(move || {
            // SAFETY: the runner guarantees the raw descriptor remains valid
            // for the duration of this child setup callback.
            let fd = BorrowedFd::borrow_raw(inherited_fd);
            let mut flags = fcntl_getfd(fd).map_err(errno_to_io)?;
            flags.remove(FdFlags::CLOEXEC);
            fcntl_setfd(fd, flags).map_err(errno_to_io)
        });
    }

    #[cfg(not(unix))]
    let _ = (command, inherited_fd);
}

#[cfg(unix)]
fn errno_to_io(error: rustix::io::Errno) -> io::Error {
    io::Error::from_raw_os_error(error.raw_os_error())
}

#[cfg(all(test, unix))]
mod tests {
    use super::*;
    use crate::test_support::temp_dir;
    use rustix::fs::{FlockOperation, flock};
    use std::{fs, time::Duration};

    #[test]
    fn request_runtime_default_preserves_explicit_settings_and_replica_context() {
        let mut command = Command::new("icp");
        configure_request_runtime(&mut command, None);
        assert_eq!(
            command
                .get_envs()
                .find(|(key, _)| *key == REQUEST_RUNTIME_WORKERS_ENV)
                .map(|(_, value)| value),
            Some(Some(OsStr::new("2")))
        );
        for value in [Some(OsStr::new("7")), Some(OsStr::new(""))] {
            let mut inherited = Command::new("icp");
            configure_request_runtime(&mut inherited, value);
            assert!(
                !inherited
                    .get_envs()
                    .any(|(key, _)| key == REQUEST_RUNTIME_WORKERS_ENV)
            );
        }
        command.env(REQUEST_RUNTIME_WORKERS_ENV, "3");
        configure_request_runtime(&mut command, None);
        assert_eq!(
            command
                .get_envs()
                .find(|(key, _)| *key == REQUEST_RUNTIME_WORKERS_ENV)
                .map(|(_, value)| value),
            Some(Some(OsStr::new("3")))
        );
        command.env_remove(REQUEST_RUNTIME_WORKERS_ENV);
        configure_request_runtime(&mut command, None);
        assert_eq!(
            command
                .get_envs()
                .find(|(key, _)| *key == REQUEST_RUNTIME_WORKERS_ENV)
                .map(|(_, value)| value),
            Some(None)
        );
        let cli = IcpCli::new("icp", None);
        for generic in [cli.command(), cli.command_in(Path::new("/tmp"))] {
            assert!(
                !generic
                    .get_envs()
                    .any(|(key, _)| key == REQUEST_RUNTIME_WORKERS_ENV)
            );
        }
    }

    #[test]
    fn configured_descriptor_lives_through_command_descendants_only() {
        let root = temp_dir("canic-icp-command-inherited-fd");
        fs::create_dir_all(&root).expect("create temp root");
        let lock_path = root.join("command.lock");
        let owner = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false)
            .open(&lock_path)
            .expect("open owner lock");
        flock(&owner, FlockOperation::NonBlockingLockExclusive).expect("lock owner file");

        let mut command = Command::new("sh");
        command.args(["-c", "sleep 0.2 & wait"]);
        configure_inherited_fd(&mut command, Some(std::os::fd::AsRawFd::as_raw_fd(&owner)));
        let mut child = command.spawn().expect("spawn inherited command tree");
        drop(owner);

        let contender = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(&lock_path)
            .expect("open contender lock");
        assert_eq!(
            flock(&contender, FlockOperation::NonBlockingLockExclusive),
            Err(rustix::io::Errno::WOULDBLOCK)
        );

        child.wait().expect("wait for command tree");
        for _ in 0..50 {
            match flock(&contender, FlockOperation::NonBlockingLockExclusive) {
                Ok(()) => {
                    fs::remove_dir_all(root).expect("remove temp root");
                    return;
                }
                Err(rustix::io::Errno::WOULDBLOCK) => {
                    std::thread::sleep(Duration::from_millis(5));
                }
                Err(error) => panic!("unexpected contender lock error: {error}"),
            }
        }
        panic!("inherited descriptor survived the command tree");
    }
}

pub(super) fn add_local_network_target(command: &mut Command) {
    command.arg(LOCAL_ICP_TARGET);
}

/// Add the selected ICP environment through ICP CLI's named-environment selector.
pub fn add_target_args(
    command: &mut Command,
    environment: Option<&str>,
    local_replica: Option<&LocalReplicaTarget>,
) {
    if let Some(environment) = environment {
        if let Some(local_replica) = local_replica
            && environment == local_replica.environment
        {
            command.env_remove("ICP_ENVIRONMENT");
            command
                .arg("-n")
                .arg(&local_replica.url)
                .arg("-k")
                .arg(&local_replica.root_key);
            return;
        }
        command.args(["-e", environment]);
    }
}

/// Add ICP CLI output formatting, handling JSON as its own flag.
pub(super) fn add_output_arg(command: &mut Command, output: &str) {
    if output == "json" {
        command.arg("--json");
    } else {
        command.args(["--output", output]);
    }
}

/// Add an ICP CLI local Candid interface path when one is available.
pub(super) fn add_candid_arg(command: &mut Command, candid_path: Option<&Path>) {
    if let Some(candid_path) = candid_path {
        command.arg("--candid").arg(candid_path);
    }
}

/// Return Canic's local ICP CLI Candid sidecar path for one role.
#[must_use]
pub fn local_canister_candid_path(
    icp_root: &Path,
    artifact_environment: &str,
    role: &str,
) -> PathBuf {
    artifact_root_path(icp_root, artifact_environment)
        .join(role)
        .join(format!("{role}.did"))
}

/// Return the local Candid sidecar path only when it exists on disk.
#[must_use]
pub fn existing_local_canister_candid_path(
    icp_root: &Path,
    artifact_environment: &str,
    role: &str,
) -> Option<PathBuf> {
    let path = local_canister_candid_path(icp_root, artifact_environment, role);
    path.is_file().then_some(path)
}

/// Add ICP CLI debug logging when requested.
pub(super) fn add_debug_arg(command: &mut Command, debug: bool) {
    if debug {
        command.arg("--debug");
    }
}

/// Ensure a command points at a supported ICP CLI executable before spawning it.
pub(super) fn ensure_command_compatible(command: &Command) -> Result<(), IcpCommandError> {
    let executable = command.get_program().to_string_lossy();
    compatible_version_output(executable.as_ref(), command.get_current_dir()).map(|_| ())
}

fn add_project_root_override_arg(command: &mut Command, cwd: &Path) {
    command.arg("--project-root-override").arg(cwd);
}

/// Render a command for diagnostics and dry-run previews.
#[must_use]
pub fn command_display(command: &Command) -> String {
    let mut parts = vec![command.get_program().to_string_lossy().to_string()];
    parts.extend(
        command
            .get_args()
            .map(|arg| arg.to_string_lossy().to_string()),
    );
    parts.join(" ")
}