canic-core 0.110.15

Canic — a canister orchestration and management toolkit for the Internet Computer
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
//! Module: ops::config
//!
//! Responsibility: expose fallible configuration lookups for ops and workflows.
//! Does not own: config parsing, environment initialization, or endpoint DTOs.
//! Boundary: ops layer between runtime context and immutable configuration model.

use crate::{
    InternalError,
    config::{
        ComponentTopology, Config, ConfigError, ConfigModel, RoleRuntimeConfig,
        RuntimeCanisterConfig, RuntimeChildCanisterAuthority,
        schema::{
            CanisterConfig, ComponentSpecConfig, CyclesFundingPolicyConfig, DelegatedTokenConfig,
            FleetInitMode, IndexConfig, LocalApplicationAuthorizationConfig, LogConfig,
            RoleAttestationConfig, ScalingConfig, implicit_root_canister_config,
            implicit_wasm_store_canister_config,
        },
    },
    dto::component_deployment::ProtectedComponentDeployment,
    ids::{CanisterRole, ComponentBinding, ComponentSpecId},
    model::cycles_funding::FundingLimits,
    ops::runtime::env::EnvOps,
    storage::stable::state::fleet::FleetMode,
};
use std::sync::Arc;
use thiserror::Error as ThisError;

///
/// ConfigOpsError
///
/// Typed failure surface for configuration lookup operations.
///

#[derive(Debug, ThisError)]
pub enum ConfigOpsError {
    #[error(transparent)]
    Config(#[from] ConfigError),

    #[error("Component Spec {0} not found in configuration")]
    ComponentSpecNotFound(String),

    #[error("canister {0} not defined in Component Spec {1}")]
    CanisterNotFound(String, String),

    #[error(
        "canister role {0} belongs to multiple Component Specs; an exact Component Spec binding is required"
    )]
    CanisterRoleAmbiguous(String),
}

impl From<ConfigOpsError> for InternalError {
    fn from(err: ConfigOpsError) -> Self {
        use crate::diagnostics::codes;

        match err {
            ConfigOpsError::Config(err) => err.into(),
            ConfigOpsError::ComponentSpecNotFound(_) | ConfigOpsError::CanisterNotFound(_, _) => {
                Self::public(codes::CONFIGURATION_UNAVAILABLE)
            }
            ConfigOpsError::CanisterRoleAmbiguous(_) => Self::public(codes::CONFIGURATION_CONFLICT),
        }
    }
}

/// Full configuration authority used only by the Root control plane.
pub struct RootConfigOps;

impl RootConfigOps {
    /// Export the full current configuration as TOML.
    /// Intended for diagnostics and tooling only.
    pub fn export_toml() -> Result<String, InternalError> {
        let toml = Config::to_toml()?;

        Ok(toml)
    }

    // ---------------------------------------------------------------------
    // Explicit / fallible lookups
    // ---------------------------------------------------------------------

    /// Fetch a Component Spec configuration by declared identity.
    pub(crate) fn try_get_component_spec(
        component_spec: &ComponentSpecId,
    ) -> Result<ComponentSpecConfig, InternalError> {
        let cfg = Config::get()?;

        cfg.get_component_spec(component_spec)
            .ok_or_else(|| ConfigOpsError::ComponentSpecNotFound(component_spec.to_string()).into())
    }

    /// Fetch a canister configuration within a specific Component Spec.
    pub(crate) fn try_get_canister(
        component_spec: &ComponentSpecId,
        canister_role: &CanisterRole,
    ) -> Result<CanisterConfig, InternalError> {
        let component_spec_cfg = Self::try_get_component_spec(component_spec)?;

        component_spec_cfg
            .get_canister(canister_role)
            .ok_or_else(|| {
                ConfigOpsError::CanisterNotFound(
                    canister_role.to_string(),
                    component_spec.to_string(),
                )
                .into()
            })
    }

    /// Compile the exact current Component Topology and its protected Spec hashes.
    pub fn component_topology() -> Result<ComponentTopology, InternalError> {
        Config::get()?
            .compile_component_topology()
            .map_err(ConfigError::from)
            .map_err(InternalError::from)
    }

    /// Validate one retained deployment context against the current compiled App authority.
    pub fn validate_protected_component_deployment(
        context: &ProtectedComponentDeployment,
        owning_component: &ComponentBinding,
    ) -> Result<(), InternalError> {
        Config::get()?
            .validate_protected_component_deployment(context, owning_component)
            .map_err(|_error| InternalError::invalid_input())
    }

    /// Resolve the exact configured package identity for one declared application role.
    pub fn role_package(canister_role: &CanisterRole) -> Result<String, InternalError> {
        let config = Config::get()?;
        config
            .roles
            .get(canister_role)
            .and_then(|declaration| declaration.package.clone())
            .ok_or_else(|| {
                ConfigOpsError::CanisterNotFound(
                    canister_role.to_string(),
                    "role declarations".to_string(),
                )
                .into()
            })
    }

    /// Resolve the explicit role-owned Fleet admission enrollment declaration.
    pub fn role_uses_fleet_admission(canister_role: &CanisterRole) -> Result<bool, InternalError> {
        let config = Config::get()?;
        config
            .role_uses_fleet_admission(canister_role)
            .ok_or_else(|| {
                ConfigOpsError::CanisterNotFound(
                    canister_role.to_string(),
                    "role declarations".to_string(),
                )
                .into()
            })
    }

    /// Resolve an implicit infrastructure role or a role structurally contained
    /// by exactly one Component Spec.
    pub fn try_get_canister_by_role(
        canister_role: &CanisterRole,
    ) -> Result<CanisterConfig, InternalError> {
        if canister_role.is_root() {
            return Ok(implicit_root_canister_config());
        }
        if canister_role.is_wasm_store() {
            return Ok(implicit_wasm_store_canister_config());
        }

        let component_spec = Self::try_get_component_spec_id_by_role(canister_role)?;
        Self::try_get_canister(&component_spec, canister_role)
    }

    /// Resolve the unique Component Spec structurally containing one role.
    fn try_get_component_spec_id_by_role(
        canister_role: &CanisterRole,
    ) -> Result<ComponentSpecId, InternalError> {
        let config = Config::get()?;
        let mut matches = config.component_specs_for_role(canister_role);
        let (component_spec, _component_spec_config) = matches.next().ok_or_else(|| {
            ConfigOpsError::CanisterNotFound(
                canister_role.to_string(),
                "Component Topology".to_string(),
            )
        })?;
        if matches.next().is_some() {
            return Err(ConfigOpsError::CanisterRoleAmbiguous(canister_role.to_string()).into());
        }

        Ok(component_spec.clone())
    }

    // ---------------------------------------------------------------------
    // Current-context / infallible helpers
    // ---------------------------------------------------------------------

    /// Return the immutable compiled App model to trusted control-plane validators.
    pub fn get() -> Result<Arc<ConfigModel>, InternalError> {
        let cfg = Config::get()?;

        Ok(cfg)
    }
}

/// Exact role-compiled runtime configuration authority.
pub struct ConfigOps;

impl ConfigOps {
    fn authority() -> Result<Arc<crate::config::RoleRuntimeAuthority>, InternalError> {
        RoleRuntimeConfig::try_get().ok_or_else(InternalError::invariant)
    }

    fn try_get_child(
        component_spec: &ComponentSpecId,
        canister_role: &CanisterRole,
    ) -> Result<RuntimeChildCanisterAuthority, InternalError> {
        Self::authority()?
            .child(component_spec, canister_role)
            .ok_or_else(|| {
                ConfigOpsError::CanisterNotFound(
                    canister_role.to_string(),
                    component_spec.to_string(),
                )
                .into()
            })
    }

    pub fn component_topology() -> Result<ComponentTopology, InternalError> {
        Ok(Self::authority()?.component_topology.clone())
    }

    pub fn validate_protected_component_deployment(
        context: &ProtectedComponentDeployment,
        owning_component: &ComponentBinding,
    ) -> Result<(), InternalError> {
        Self::authority()?.validate_protected_component_deployment(context, owning_component)
    }

    pub fn role_uses_fleet_admission(canister_role: &CanisterRole) -> Result<bool, InternalError> {
        let authority = Self::authority()?;
        (&authority.role == canister_role)
            .then_some(authority.fleet_admission)
            .ok_or_else(|| {
                ConfigOpsError::CanisterNotFound(
                    canister_role.to_string(),
                    "compiled runtime role".to_string(),
                )
                .into()
            })
    }

    pub(crate) fn log_config() -> Result<LogConfig, InternalError> {
        Ok(Self::authority()?.log.clone())
    }

    pub(crate) fn delegated_tokens_config() -> Result<DelegatedTokenConfig, InternalError> {
        Ok(Self::authority()?.auth.delegated_tokens.clone())
    }

    pub(crate) fn role_attestation_config() -> Result<RoleAttestationConfig, InternalError> {
        Ok(Self::authority()?.auth.role_attestation.clone())
    }

    pub(crate) fn local_application_authorization_for_role(
        role: &CanisterRole,
    ) -> Option<LocalApplicationAuthorizationConfig> {
        RoleRuntimeConfig::try_get()?.local_application_authorization(role)
    }

    pub(crate) fn app_init_mode() -> Result<FleetMode, InternalError> {
        let mode = match Self::authority()?.app_init_mode {
            FleetInitMode::Enabled => FleetMode::Enabled,
            FleetInitMode::Readonly => FleetMode::Readonly,
            FleetInitMode::Disabled => FleetMode::Disabled,
        };
        Ok(mode)
    }

    pub(crate) fn current_canister() -> Result<RuntimeCanisterConfig, InternalError> {
        let canister_role = EnvOps::canister_role()?;
        let component_spec = if canister_role.is_root() || canister_role.is_wasm_store() {
            None
        } else {
            Some(EnvOps::component_spec()?)
        };
        Self::authority()?
            .canister(component_spec.as_ref(), &canister_role)
            .ok_or_else(|| {
                ConfigOpsError::CanisterNotFound(
                    canister_role.to_string(),
                    component_spec.map_or_else(
                        || "infrastructure".to_string(),
                        |component_spec| component_spec.to_string(),
                    ),
                )
                .into()
            })
    }

    pub(crate) fn current_scaling_config() -> Result<Option<ScalingConfig>, InternalError> {
        Ok(Self::current_canister()?.scaling)
    }

    pub(crate) fn current_index_config() -> Result<Option<IndexConfig>, InternalError> {
        Ok(Self::current_canister()?.index)
    }

    pub(crate) fn current_component_child(
        canister_role: &CanisterRole,
    ) -> Result<RuntimeChildCanisterAuthority, InternalError> {
        let component_spec = EnvOps::component_spec()?;
        Self::try_get_child(&component_spec, canister_role)
    }

    pub(crate) fn current_icrc21_enabled() -> bool {
        Self::authority().is_ok_and(|authority| {
            authority.global_icrc21
                && Self::current_canister().is_ok_and(|canister| canister.standards.icrc21)
        })
    }

    pub(crate) fn cycles_funding_limits_for_root_child_role(
        child_role: &CanisterRole,
    ) -> Result<FundingLimits, InternalError> {
        let child = RootConfigOps::try_get_canister_by_role(child_role)?;
        Ok(funding_limits(&child.cycles_funding))
    }

    pub(crate) fn cycles_funding_limits_for_component_child_role(
        child_role: &CanisterRole,
    ) -> Result<FundingLimits, InternalError> {
        let child = Self::current_component_child(child_role)?;
        Ok(funding_limits(&child.cycles_funding))
    }
}

const fn funding_limits(policy: &CyclesFundingPolicyConfig) -> FundingLimits {
    FundingLimits {
        max_per_request: policy.max_per_request.to_u128(),
        max_per_child: policy.max_per_child.to_u128(),
        cooldown_secs: policy.cooldown_secs,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        cdk::types::Cycles,
        config::schema::{CanisterKind, CyclesFundingPolicyConfig},
        storage::stable::env::{Env, EnvData, EnvRecord},
        test::config::ConfigTestBuilder,
    };

    #[test]
    fn role_lookup_resolves_implicit_infrastructure_outside_component_topology() {
        let root = RootConfigOps::try_get_canister_by_role(&CanisterRole::ROOT)
            .expect("implicit root config");
        let wasm_store = RootConfigOps::try_get_canister_by_role(&CanisterRole::WASM_STORE)
            .expect("implicit Wasm Store config");

        assert_eq!(root.kind, CanisterKind::Root);
        assert_eq!(wasm_store.kind, CanisterKind::Singleton);
    }

    #[test]
    fn ordinary_runtime_lookup_requires_its_exact_component_spec() {
        let role = CanisterRole::from("app");
        let child_role = CanisterRole::from("child");
        let mut child = ConfigTestBuilder::canister_config(CanisterKind::Singleton);
        child.cycles_funding = CyclesFundingPolicyConfig {
            max_per_request: Cycles::new(10),
            max_per_child: Cycles::new(30),
            cooldown_secs: 60,
        };
        let _config = ConfigTestBuilder::new()
            .with_default_canister(child_role.clone(), child)
            .install();

        let original_env = Env::export();
        let component_spec =
            ComponentSpecId::try_from("default".to_string()).expect("default Component Spec ID");
        Env::import(EnvData {
            record: EnvRecord {
                canister_role: Some(role),
                component_spec: Some(component_spec),
                ..EnvRecord::default()
            },
        });
        ConfigOps::current_canister().expect("exact ordinary runtime config");
        let child = ConfigOps::current_component_child(&child_role)
            .expect("exact compact child runtime authority");
        assert_eq!(child.kind, CanisterKind::Singleton);
        assert_eq!(child.cycles_funding.max_per_request.to_u128(), 10);
        assert_eq!(child.cycles_funding.max_per_child.to_u128(), 30);
        assert_eq!(child.cycles_funding.cooldown_secs, 60);
        let limits = ConfigOps::cycles_funding_limits_for_component_child_role(&child_role)
            .expect("compact child funding limits");
        assert_eq!(limits.max_per_request, 10);
        assert_eq!(limits.max_per_child, 30);
        assert_eq!(limits.cooldown_secs, 60);

        let mut missing_component_spec = Env::export();
        missing_component_spec.record.component_spec = None;
        Env::import(missing_component_spec);
        assert!(ConfigOps::current_canister().is_err());

        Env::import(original_env);
        Config::reset_for_tests();
    }
}