canic-host 0.100.12

Host-side App build, Fleet install, deployment, and release-set 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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
use crate::{
    canister_build::cache::DefaultCanisterBuildCacheCleanup,
    deployment_truth::DeploymentReceiptV1,
    fleet_install_input::{ResolvedFleetInstallInput, load_and_resolve_fleet_install_input},
    fleet_install_plan::{
        FleetInstallPlanRequest, PersistedFleetInstallPlan, compile_and_persist_fleet_install_plan,
    },
    network::resolve_canonical_network_id_from_root,
    release_set::{AppConfigSnapshot, icp_root, workspace_root},
};
use config_selection::resolve_install_config_path;
use std::{
    fmt,
    path::{Path, PathBuf},
    time::{Duration, Instant},
};
use thiserror::Error as ThisError;

mod activation;
mod build_network;
mod build_snapshot;
mod build_targets;
mod capabilities;
mod clock;
mod commands;
mod config_selection;
mod coordinator_install;
mod coordinator_install_journal;
mod current_execution;
mod deployment_truth_gate;
mod execution_preflight;
mod fleet_activation_journal;
mod identity;
mod operations;
mod options;
mod output;
mod phase_receipts;
mod plan_artifacts;
mod preparation;
mod receipt_io;
mod root_canister;
mod root_cycles;
mod timing;
mod truth_check;

use crate::release_build::{ReleaseBuildPlanError, plan_release_build};
use activation::install_root_committed;
use build_network::resolve_install_build_context;
use build_snapshot::resolve_install_snapshot;
pub use config_selection::{
    ConfigDiscoveryError, current_canic_project_root, discover_canic_config_choices,
    discover_canic_project_root_from, discover_project_canic_config_choices, project_app_roots,
    select_discovered_app_config_path,
};
use coordinator_install::install_and_verify_fleet_coordinator;
use current_execution::current_install_execution_context;
use identity::resolve_install_identity;
pub use operations::{
    InstallRootActivationStatusError, InstallRootExecutionReconciliationError,
    InstallRootModuleVerificationError,
};
pub use options::InstallRootOptions;
use output::print_install_timing_summary;
pub use phase_receipts::InstallPhaseFailureError;
use phase_receipts::{
    CompletedInstallPhase, InstallReceiptScope, write_completed_install_phase_receipt,
};
use plan_artifacts::emit_manifest_with_phase;
use preparation::{prepare_install_deployment_truth, resolve_root_canister_after_manifest};
use receipt_io::install_deployment_truth_receipts_dir;
pub use receipt_io::latest_deployment_truth_receipt_path_from_root;
use timing::InstallTimingSummary as CurrentInstallTimingSummary;
pub use truth_check::{check_install_deployment_truth, check_install_execution_preflight};

#[cfg(test)]
mod tests;

///
/// InstallRootBlockKind
///
/// Machine-readable reason that a fresh root install stopped before mutation.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum InstallRootBlockKind {
    DeploymentExecutionPreflight,
    DeploymentTruth,
}

///
/// InstallRootBlockedError
///
/// Typed install block retained through the host/CLI error boundary.
///

#[derive(Debug, ThisError)]
#[error("{message}")]
pub struct InstallRootBlockedError {
    kind: InstallRootBlockKind,
    message: String,
}

impl InstallRootBlockedError {
    pub(super) const fn new(kind: InstallRootBlockKind, message: String) -> Self {
        Self { kind, message }
    }

    #[must_use]
    pub const fn kind(&self) -> InstallRootBlockKind {
        self.kind
    }
}

/// Stable phase in which a root install failed.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum InstallRootPhase {
    WorkspaceDiscovery,
    ProjectDiscovery,
    Configuration,
    BuildInputs,
    Identity,
    Preparation,
    Manifest,
    Planning,
    Activation,
}

impl fmt::Display for InstallRootPhase {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::WorkspaceDiscovery => "workspace discovery",
            Self::ProjectDiscovery => "ICP project discovery",
            Self::Configuration => "configuration selection",
            Self::BuildInputs => "build input validation",
            Self::Identity => "deployment identity resolution",
            Self::Preparation => "deployment preparation",
            Self::Manifest => "manifest emission",
            Self::Planning => "Fleet installation planning",
            Self::Activation => "root activation",
        })
    }
}

/// Typed public failure for the root-install workflow.
#[derive(Debug, ThisError)]
#[error("root install failed during {phase}: {source}")]
pub struct InstallRootError {
    phase: InstallRootPhase,
    #[source]
    source: Box<dyn std::error::Error>,
}

impl InstallRootError {
    /// Preserve a concrete cause while assigning it to a stable install phase.
    pub fn new<E>(phase: InstallRootPhase, source: E) -> Self
    where
        E: std::error::Error + 'static,
    {
        Self {
            phase,
            source: Box::new(source),
        }
    }

    fn from_boxed(phase: InstallRootPhase, source: Box<dyn std::error::Error>) -> Self {
        Self { phase, source }
    }

    fn in_phase(phase: InstallRootPhase) -> impl FnOnce(Box<dyn std::error::Error>) -> Self {
        move |source| Self::from_boxed(phase, source)
    }

    #[must_use]
    pub const fn phase(&self) -> InstallRootPhase {
        self.phase
    }
}

#[derive(Debug, ThisError)]
#[error(
    "Fleet Coordinator {coordinator} is installed and independently verified from the durable plan at {}; Fleet Subnet Root effects remain blocked until the planned multi-root lifecycle is implemented",
    plan_path.display(),
)]
struct FleetRootEffectsUnavailableError {
    plan_path: PathBuf,
    coordinator: canic_core::cdk::types::Principal,
}

#[derive(Debug, ThisError)]
#[error("fresh Fleet installation requires --fleet-input <PATH>")]
struct MissingFleetInstallInputError;

/// Discover installable Canic config choices under the current workspace.
pub fn discover_current_canic_config_choices() -> Result<Vec<PathBuf>, ConfigDiscoveryError> {
    let project_root = current_canic_project_root()?;
    let choices = config_selection::discover_workspace_canic_config_choices(&project_root)?;
    if !choices.is_empty() {
        return Ok(choices);
    }

    let icp_root = icp_root()?;
    if icp_root != project_root {
        return config_selection::discover_workspace_canic_config_choices(&icp_root);
    }

    Ok(choices)
}

// Execute fresh Fleet planning and the Coordinator-first installation workflow.
pub fn install_root(options: InstallRootOptions) -> Result<(), InstallRootError> {
    let (workspace_root, icp_root) = resolve_current_install_roots(&options)?;
    let _build_cache_cleanup = DefaultCanisterBuildCacheCleanup::for_install(&workspace_root);
    let config_path = current_install_config_path(&icp_root, &options)?;
    let (build_context, install_snapshot) =
        current_install_build_inputs(&workspace_root, &icp_root, &config_path, &options)
            .map_err(InstallRootError::in_phase(InstallRootPhase::BuildInputs))?;
    let (app_id, fleet_name) =
        resolve_install_identity(&options, &config_path, &install_snapshot.app_id)
            .map_err(InstallRootError::in_phase(InstallRootPhase::Identity))?;
    let total_started_at = Instant::now();
    let mut timings = CurrentInstallTimingSummary::default();
    let environment = options.environment.as_str();
    let execution_context = current_install_execution_context(
        &workspace_root,
        &icp_root,
        options.artifact_environment(),
    );
    let resolved_fleet_install_input =
        resolve_current_fleet_install_input(&icp_root, environment, &options)
            .map_err(InstallRootError::in_phase(InstallRootPhase::Planning))?;

    print_install_identity(&app_id, &fleet_name);
    let prepared = prepare_install_deployment_truth(
        &options,
        &icp_root,
        &config_path,
        &fleet_name,
        &execution_context,
        &build_context,
        &install_snapshot,
    )
    .map_err(InstallRootError::in_phase(InstallRootPhase::Preparation))?;
    timings.build_all = prepared.timings.build_all;
    let emitted_manifest = emit_manifest_with_phase(
        &icp_root,
        &install_snapshot,
        &prepared.build_outputs,
        &prepared.infrastructure_build_outputs,
        prepared.plan_artifacts.as_ref(),
    )
    .map_err(InstallRootError::in_phase(InstallRootPhase::Manifest))?;
    timings.emit_manifest = emitted_manifest.duration;
    let finalized_release_build =
        require_finalized_release_build(emitted_manifest.finalized_release_build)?;
    let planned_install = plan_current_fleet_install(
        &icp_root,
        environment,
        &fleet_name,
        &app_id,
        &config_path,
        &finalized_release_build,
        resolved_fleet_install_input,
    )?;
    let receipt_scope = InstallReceiptScope {
        icp_root: &icp_root,
        environment,
        fleet: planned_install.fleet(),
        check: &prepared.deployment_truth_check,
        execution_context: Some(&execution_context),
    };
    persist_current_pre_root_receipts(
        receipt_scope,
        &prepared.pre_activation_receipts,
        prepared.build_phase,
        emitted_manifest.phase,
    )?;
    let (coordinator, coordinator_duration) = install_current_fleet_coordinator(
        &icp_root,
        environment,
        build_context.local_replica.as_ref(),
        &config_path,
        &planned_install.plan,
    )?;
    timings.create_canisters = coordinator_duration;
    require_fleet_subnet_root_install_effects(&planned_install.plan.path, coordinator.coordinator)
        .map_err(|source| InstallRootError::new(InstallRootPhase::Activation, source))?;
    let (root_canister_id, create_duration) = resolve_or_recover_activation_root(
        &planned_install.activation,
        receipt_scope,
        &options,
        &config_path,
        &build_context,
    )
    .map_err(InstallRootError::in_phase(InstallRootPhase::Activation))?;
    timings.create_canisters += create_duration;
    let committed_root = install_root_committed(
        receipt_scope,
        &options,
        &root_canister_id,
        &build_context,
        prepared.plan_artifacts.as_ref(),
        &planned_install.activation,
    )
    .map_err(InstallRootError::in_phase(InstallRootPhase::Activation))?;
    timings.record_activation(committed_root.timings);

    print_install_timing_summary(&timings, total_started_at.elapsed());
    Ok(())
}

fn resolve_current_install_roots(
    options: &InstallRootOptions,
) -> Result<(PathBuf, PathBuf), InstallRootError> {
    let workspace_root = workspace_root()
        .map_err(|source| InstallRootError::new(InstallRootPhase::WorkspaceDiscovery, source))?;
    let icp_root = match &options.icp_root {
        Some(path) => path
            .canonicalize()
            .map_err(|source| InstallRootError::new(InstallRootPhase::ProjectDiscovery, source))?,
        None => icp_root()
            .map_err(|source| InstallRootError::new(InstallRootPhase::ProjectDiscovery, source))?,
    };
    Ok((workspace_root, icp_root))
}

fn plan_current_fleet_install(
    icp_root: &Path,
    environment: &str,
    fleet_name: &str,
    app_id: &str,
    config_path: &Path,
    finalized_release_build: &crate::release_build::FinalizedReleaseBuild,
    input: ResolvedFleetInstallInput,
) -> Result<PlannedCurrentFleetInstall, InstallRootError> {
    let activation = plan_current_fleet_activation(
        icp_root,
        environment,
        fleet_name,
        app_id,
        finalized_release_build,
    )?;
    let plan = persist_current_fleet_install_plan(
        icp_root,
        config_path,
        activation.journal.activation.identity.fleet.clone(),
        finalized_release_build,
        input,
    )
    .map_err(InstallRootError::in_phase(InstallRootPhase::Planning))?;
    Ok(PlannedCurrentFleetInstall { activation, plan })
}

struct PlannedCurrentFleetInstall {
    activation: fleet_activation_journal::ResolvedFleetInstallActivation,
    plan: PersistedFleetInstallPlan,
}

impl PlannedCurrentFleetInstall {
    const fn fleet(&self) -> canic_core::ids::FleetKey {
        self.activation.journal.activation.identity.fleet.fleet
    }
}

fn require_finalized_release_build(
    finalized: Option<crate::release_build::FinalizedReleaseBuild>,
) -> Result<crate::release_build::FinalizedReleaseBuild, InstallRootError> {
    finalized.ok_or_else(|| {
        InstallRootError::new(
            InstallRootPhase::Manifest,
            ReleaseBuildPlanError::MissingFinalizedAuthority,
        )
    })
}

fn resolve_current_fleet_install_input(
    icp_root: &Path,
    environment: &str,
    options: &InstallRootOptions,
) -> Result<ResolvedFleetInstallInput, Box<dyn std::error::Error>> {
    let input_path = options
        .fleet_install_input_path
        .as_ref()
        .ok_or(MissingFleetInstallInputError)?;
    let input_path = if input_path.is_absolute() {
        input_path.clone()
    } else {
        icp_root.join(input_path)
    };
    load_and_resolve_fleet_install_input(icp_root, environment, &input_path).map_err(Into::into)
}

fn persist_current_fleet_install_plan(
    icp_root: &Path,
    config_path: &Path,
    fleet: canic_core::ids::FleetBinding,
    finalized_release_build: &crate::release_build::FinalizedReleaseBuild,
    input: ResolvedFleetInstallInput,
) -> Result<PersistedFleetInstallPlan, Box<dyn std::error::Error>> {
    let config = AppConfigSnapshot::load(config_path)?;
    compile_and_persist_fleet_install_plan(FleetInstallPlanRequest {
        root: icp_root,
        config: config.model(),
        fleet,
        release_build_id: finalized_release_build.record.release_build_id,
        coordinator: input.coordinator,
        fleet_subnet_roots: input.fleet_subnet_roots,
    })
    .map_err(Into::into)
}

fn require_fleet_subnet_root_install_effects(
    plan_path: &Path,
    coordinator: canic_core::cdk::types::Principal,
) -> Result<(), FleetRootEffectsUnavailableError> {
    Err(FleetRootEffectsUnavailableError {
        plan_path: plan_path.to_path_buf(),
        coordinator,
    })
}

fn current_install_config_path(
    icp_root: &Path,
    options: &InstallRootOptions,
) -> Result<PathBuf, InstallRootError> {
    resolve_install_config_path(
        icp_root,
        options.config_path.as_deref(),
        options.interactive_config_selection,
    )
    .map_err(InstallRootError::in_phase(InstallRootPhase::Configuration))
}

fn plan_current_fleet_activation(
    icp_root: &Path,
    environment: &str,
    fleet_name: &str,
    app_id: &str,
    finalized_release_build: &crate::release_build::FinalizedReleaseBuild,
) -> Result<fleet_activation_journal::ResolvedFleetInstallActivation, InstallRootError> {
    let canonical_network_id = resolve_canonical_network_id_from_root(icp_root, environment)
        .map_err(|source| InstallRootError::new(InstallRootPhase::Activation, source))?;
    let fleet_name = fleet_name
        .parse()
        .map_err(|source| InstallRootError::new(InstallRootPhase::Identity, source))?;
    fleet_activation_journal::plan_fleet_install_activation(
        fleet_activation_journal::PlanFleetInstallActivationRequest {
            root: icp_root,
            canonical_network_id,
            fleet_name,
            app: app_id.into(),
            finalized_release_build,
        },
    )
    .map_err(|source| InstallRootError::new(InstallRootPhase::Activation, source))
}

fn resolve_or_recover_activation_root(
    activation: &fleet_activation_journal::ResolvedFleetInstallActivation,
    receipt_scope: InstallReceiptScope<'_>,
    options: &InstallRootOptions,
    config_path: &Path,
    build_context: &crate::canister_build::WorkspaceBuildContext,
) -> Result<(String, Duration), Box<dyn std::error::Error>> {
    let receipt_directory =
        install_deployment_truth_receipts_dir(receipt_scope.icp_root, receipt_scope.fleet);
    match fleet_activation_journal::recover_activation_root_canister(
        activation,
        &receipt_directory,
    )? {
        Some(root_canister) => Ok((root_canister.to_text(), Duration::ZERO)),
        None => {
            resolve_root_canister_after_manifest(receipt_scope, options, config_path, build_context)
        }
    }
}

fn print_install_identity(app: &str, fleet_name: &str) {
    println!("Installing Fleet {fleet_name}");
    println!("Source App {app}");
    println!();
}

fn persist_current_pre_root_receipts(
    receipt_scope: InstallReceiptScope<'_>,
    prepared_receipts: &[DeploymentReceiptV1],
    build_phase: CompletedInstallPhase,
    manifest_phase: CompletedInstallPhase,
) -> Result<(), InstallRootError> {
    persist_pre_root_receipts(
        receipt_scope,
        prepared_receipts,
        build_phase,
        manifest_phase,
    )
    .map_err(InstallRootError::in_phase(InstallRootPhase::Activation))
}

fn install_current_fleet_coordinator(
    icp_root: &Path,
    environment: &str,
    local_replica: Option<&crate::icp::LocalReplicaTarget>,
    config_path: &Path,
    plan: &PersistedFleetInstallPlan,
) -> Result<(coordinator_install::VerifiedFleetCoordinator, Duration), InstallRootError> {
    let started = Instant::now();
    let coordinator = install_and_verify_fleet_coordinator(
        icp_root,
        environment,
        local_replica,
        config_path,
        plan,
    )
    .map_err(InstallRootError::in_phase(InstallRootPhase::Activation))?;
    Ok((coordinator, started.elapsed()))
}

fn persist_pre_root_receipts(
    receipt_scope: InstallReceiptScope<'_>,
    prepared_receipts: &[DeploymentReceiptV1],
    build_phase: CompletedInstallPhase,
    manifest_phase: CompletedInstallPhase,
) -> Result<(), Box<dyn std::error::Error>> {
    for receipt in prepared_receipts {
        receipt_scope.write_receipt(receipt)?;
    }
    write_completed_install_phase_receipt(receipt_scope, build_phase)?;
    write_completed_install_phase_receipt(receipt_scope, manifest_phase)?;
    Ok(())
}

fn current_install_build_inputs(
    workspace_root: &std::path::Path,
    icp_root: &std::path::Path,
    config_path: &std::path::Path,
    options: &InstallRootOptions,
) -> Result<
    (
        crate::canister_build::WorkspaceBuildContext,
        build_snapshot::ValidatedInstallSnapshot,
    ),
    Box<dyn std::error::Error>,
> {
    let mut context = resolve_install_build_context(
        workspace_root,
        icp_root,
        config_path,
        &options.environment,
        &options.root_build_target,
        options.build_profile,
    )?;
    let mut snapshot = resolve_install_snapshot(
        &context,
        &options.root_build_target,
        options.deployment_plan_override.is_some(),
    )?;
    if snapshot.complete_build.is_some() {
        let release_build = plan_release_build(icp_root)?;
        context = context.with_release_build_id(release_build.record.release_build_id);
        snapshot.release_build = Some(release_build);
    }
    Ok((context, snapshot))
}