canic-core 0.100.17

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
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
//! Module: config::validation::component_spec
//!
//! Responsibility: validate Component Spec catalogs, spawn grants, placement, and refill policy.
//! Does not own: topology workflow, placement policy execution, or schema definitions.
//! Boundary: config validation calls this before runtime installation.

use crate::{
    config::schema::{
        CanisterConfig, ComponentChildKind, ComponentSpecConfig, ConfigSchemaError,
        CyclesFundingPolicyConfig, MAX_COMPONENT_CHILD_ROLES, MAX_COMPONENT_PROVISIONING_GRANTS,
        MAX_COMPONENT_SPAWN_GRANTS, NAME_MAX_BYTES, TopupPolicy, Validate,
    },
    config::validation::validate_canister_role,
    ids::CanisterRole,
};
use std::collections::BTreeMap;

impl Validate for ComponentSpecConfig {
    fn validate(&self) -> Result<(), ConfigSchemaError> {
        validate_canister_role(&self.component_role, "Component role")?;
        if self.component_role.is_fleet_coordinator()
            || self.component_role.is_root()
            || self.component_role.is_wasm_store()
        {
            return Err(ConfigSchemaError::ValidationError(format!(
                "Component role '{}' is reserved infrastructure",
                self.component_role,
            )));
        }
        if self.maximum_instances == 0 {
            return Err(ConfigSchemaError::ValidationError(format!(
                "Component '{}' maximum_instances must be > 0",
                self.component_role,
            )));
        }
        if self.children.len() > MAX_COMPONENT_CHILD_ROLES {
            return Err(ConfigSchemaError::ValidationError(format!(
                "Component '{}' declares {} child roles, exceeding bound {MAX_COMPONENT_CHILD_ROLES}",
                self.component_role,
                self.children.len(),
            )));
        }
        if self.provisions.len() > MAX_COMPONENT_PROVISIONING_GRANTS {
            return Err(ConfigSchemaError::ValidationError(format!(
                "Component '{}' declares {} provisioning grants, exceeding bound {MAX_COMPONENT_PROVISIONING_GRANTS}",
                self.component_role,
                self.provisions.len(),
            )));
        }
        if !self.children.is_empty() && self.limits.maximum_descendants == 0 {
            return Err(ConfigSchemaError::ValidationError(format!(
                "Component '{}' limits.maximum_descendants must be > 0 when child roles are declared",
                self.component_role,
            )));
        }
        if self.limits.maximum_registry_bytes == 0 {
            return Err(ConfigSchemaError::ValidationError(format!(
                "Component '{}' limits.maximum_registry_bytes must be > 0",
                self.component_role,
            )));
        }
        if self.limits.cycles_funding.window_secs == 0 {
            return Err(ConfigSchemaError::ValidationError(format!(
                "Component '{}' limits.cycles_funding.window_secs must be > 0",
                self.component_role,
            )));
        }
        if self.limits.cycles_funding.maximum_cycles.to_u128() == 0 {
            return Err(ConfigSchemaError::ValidationError(format!(
                "Component '{}' limits.cycles_funding.maximum_cycles must be > 0",
                self.component_role,
            )));
        }

        validate_cycles_funding(&self.cycles_funding, &self.component_role)?;
        validate_topup(self.topup.as_ref(), &self.component_role)?;

        validate_component_children(self)?;
        validate_spawn_grants(self)?;
        validate_provisioning_grant_limits(self)?;

        validate_placement_policies(
            self,
            &self.component_role,
            &self.component_canister_config(),
        )?;
        for (role, child) in &self.children {
            validate_placement_policies(self, role, &child.canister_config())?;
        }

        Ok(())
    }
}

fn validate_component_children(config: &ComponentSpecConfig) -> Result<(), ConfigSchemaError> {
    for (role, child) in &config.children {
        validate_canister_role(role, "Component child role")?;
        if role == &config.component_role {
            return Err(ConfigSchemaError::ValidationError(format!(
                "Component '{}' cannot also be its own child",
                config.component_role,
            )));
        }
        if role.is_fleet_coordinator() || role.is_root() || role.is_wasm_store() {
            return Err(ConfigSchemaError::ValidationError(format!(
                "Component Child '{role}' is reserved infrastructure",
            )));
        }
        validate_cycles_funding(&child.cycles_funding, role)?;
        validate_topup(child.topup.as_ref(), role)?;
    }

    Ok(())
}

fn validate_spawn_grants(config: &ComponentSpecConfig) -> Result<(), ConfigSchemaError> {
    let grant_count = config
        .spawn_grants
        .values()
        .try_fold(0_usize, |count, grants| count.checked_add(grants.len()));
    let Some(grant_count) = grant_count else {
        return Err(ConfigSchemaError::ValidationError(format!(
            "Component '{}' spawn grant count overflowed",
            config.component_role,
        )));
    };
    if grant_count > MAX_COMPONENT_SPAWN_GRANTS {
        return Err(ConfigSchemaError::ValidationError(format!(
            "Component '{}' declares {grant_count} spawn grants, exceeding bound {MAX_COMPONENT_SPAWN_GRANTS}",
            config.component_role,
        )));
    }

    let mut incoming = BTreeMap::<&CanisterRole, usize>::new();
    for (parent_role, grants) in &config.spawn_grants {
        if parent_role != &config.component_role && !config.children.contains_key(parent_role) {
            return Err(ConfigSchemaError::ValidationError(format!(
                "Component '{}' spawn grants reference undeclared parent role '{parent_role}'",
                config.component_role,
            )));
        }

        for (child_role, grant) in grants {
            let Some(child) = config.children.get(child_role) else {
                return Err(ConfigSchemaError::ValidationError(format!(
                    "Component '{}' spawn grant '{parent_role}' -> '{child_role}' references an undeclared child role",
                    config.component_role,
                )));
            };
            if grant.maximum_instances_per_parent == 0 {
                return Err(ConfigSchemaError::ValidationError(format!(
                    "Component '{}' spawn grant '{parent_role}' -> '{child_role}' maximum_instances_per_parent must be > 0",
                    config.component_role,
                )));
            }
            if child.kind == ComponentChildKind::Singleton
                && grant.maximum_instances_per_parent != 1
            {
                return Err(ConfigSchemaError::ValidationError(format!(
                    "singleton Component Child '{child_role}' spawn grants must set maximum_instances_per_parent = 1",
                )));
            }
            *incoming.entry(child_role).or_default() += 1;
        }
    }

    for child_role in config.children.keys() {
        if !incoming.contains_key(child_role) {
            return Err(ConfigSchemaError::ValidationError(format!(
                "Component '{}' child role '{child_role}' has no incoming spawn grant",
                config.component_role,
            )));
        }
    }

    Ok(())
}

fn validate_provisioning_grant_limits(
    config: &ComponentSpecConfig,
) -> Result<(), ConfigSchemaError> {
    for (target, grant) in &config.provisions {
        if grant.maximum_instances_per_requester_per_root == 0 {
            return Err(ConfigSchemaError::ValidationError(format!(
                "Component provisioning grant to '{target}' maximum_instances_per_requester_per_root must be > 0",
            )));
        }
    }

    Ok(())
}

fn validate_cycles_funding(
    policy: &CyclesFundingPolicyConfig,
    canister: &CanisterRole,
) -> Result<(), ConfigSchemaError> {
    let max_per_request = policy.max_per_request.to_u128();
    let max_per_child = policy.max_per_child.to_u128();

    if max_per_request == 0 {
        return Err(ConfigSchemaError::ValidationError(format!(
            "canister '{canister}' cycles_funding.max_per_request must be > 0",
        )));
    }

    if max_per_child == 0 {
        return Err(ConfigSchemaError::ValidationError(format!(
            "canister '{canister}' cycles_funding.max_per_child must be > 0",
        )));
    }

    if policy.cooldown_secs == 0 {
        return Err(ConfigSchemaError::ValidationError(format!(
            "canister '{canister}' cycles_funding.cooldown_secs must be > 0",
        )));
    }

    if max_per_request > max_per_child {
        return Err(ConfigSchemaError::ValidationError(format!(
            "canister '{canister}' cycles_funding.max_per_request must be <= cycles_funding.max_per_child",
        )));
    }

    Ok(())
}

fn validate_topup(
    topup: Option<&TopupPolicy>,
    canister: &CanisterRole,
) -> Result<(), ConfigSchemaError> {
    let Some(topup) = topup else {
        return Ok(());
    };

    let threshold = topup.threshold.to_u128();
    let amount = topup.amount.to_u128();

    if amount.saturating_mul(2) > threshold {
        return Err(ConfigSchemaError::ValidationError(format!(
            "canister '{canister}' topup.amount must be <= 50% of topup.threshold (got amount={amount}, threshold={threshold})",
        )));
    }

    Ok(())
}

fn validate_placement_policies(
    cfg: &ComponentSpecConfig,
    role: &CanisterRole,
    canister: &CanisterConfig,
) -> Result<(), ConfigSchemaError> {
    validate_scaling(cfg, role, canister)?;
    validate_sharding(cfg, role, canister)?;
    validate_index(cfg, role, canister)
}

fn spawn_limit(
    cfg: &ComponentSpecConfig,
    parent_role: &CanisterRole,
    child_role: &CanisterRole,
) -> Result<u32, ConfigSchemaError> {
    cfg.spawn_grants
        .get(parent_role)
        .and_then(|grants| grants.get(child_role))
        .map(|grant| grant.maximum_instances_per_parent)
        .ok_or_else(|| {
            ConfigSchemaError::ValidationError(format!(
                "Component '{}' placement policy for '{parent_role}' targets '{child_role}' without a matching spawn grant",
                cfg.component_role,
            ))
        })
}

fn validate_sharding(
    cfg: &ComponentSpecConfig,
    role: &CanisterRole,
    canister: &CanisterConfig,
) -> Result<(), ConfigSchemaError> {
    let Some(sharding) = &canister.sharding else {
        return Ok(());
    };

    for (pool_name, pool) in &sharding.pools {
        if pool_name.len() > NAME_MAX_BYTES {
            return Err(ConfigSchemaError::ValidationError(format!(
                "canister '{role}' sharding pool '{pool_name}' name exceeds {NAME_MAX_BYTES} bytes",
            )));
        }

        if !cfg.children.contains_key(&pool.canister_role) {
            return Err(ConfigSchemaError::ValidationError(format!(
                "Component '{role}' sharding pool '{pool_name}' references undeclared child role '{}'",
                pool.canister_role
            )));
        }

        let target = &cfg.children[&pool.canister_role];
        if target.kind != ComponentChildKind::Shard {
            return Err(ConfigSchemaError::ValidationError(format!(
                "Component '{role}' sharding pool '{pool_name}' references child '{}' which is not kind = \"shard\"",
                pool.canister_role
            )));
        }

        if pool.policy.capacity == 0 || pool.policy.max_shards == 0 {
            return Err(ConfigSchemaError::ValidationError(format!(
                "canister '{role}' sharding pool '{pool_name}' must have positive capacity and max_shards",
            )));
        }

        if pool.policy.initial_shards > pool.policy.max_shards {
            return Err(ConfigSchemaError::ValidationError(format!(
                "canister '{role}' sharding pool '{pool_name}' has initial_shards > max_shards",
            )));
        }

        let maximum_instances_per_parent = spawn_limit(cfg, role, &pool.canister_role)?;
        if pool.policy.max_shards > maximum_instances_per_parent {
            return Err(ConfigSchemaError::ValidationError(format!(
                "Component '{role}' sharding pool '{pool_name}' max_shards exceeds spawn grant to '{}' maximum_instances_per_parent",
                pool.canister_role,
            )));
        }
    }

    Ok(())
}

fn validate_scaling(
    cfg: &ComponentSpecConfig,
    role: &CanisterRole,
    canister: &CanisterConfig,
) -> Result<(), ConfigSchemaError> {
    let Some(scaling) = &canister.scaling else {
        return Ok(());
    };

    for (pool_name, pool) in &scaling.pools {
        if pool_name.len() > NAME_MAX_BYTES {
            return Err(ConfigSchemaError::ValidationError(format!(
                "canister '{role}' scaling pool '{pool_name}' name exceeds {NAME_MAX_BYTES} bytes",
            )));
        }

        if !cfg.children.contains_key(&pool.canister_role) {
            return Err(ConfigSchemaError::ValidationError(format!(
                "Component '{role}' scaling pool '{pool_name}' references undeclared child role '{}'",
                pool.canister_role
            )));
        }

        let target = &cfg.children[&pool.canister_role];
        if target.kind != ComponentChildKind::Replica {
            return Err(ConfigSchemaError::ValidationError(format!(
                "Component '{role}' scaling pool '{pool_name}' references child '{}' which is not kind = \"replica\"",
                pool.canister_role
            )));
        }

        if pool.policy.max_workers != 0 && pool.policy.max_workers < pool.policy.min_workers {
            return Err(ConfigSchemaError::ValidationError(format!(
                "canister '{role}' scaling pool '{pool_name}' has max_workers < min_workers",
            )));
        }

        if pool.policy.max_workers != 0 && pool.policy.max_workers < pool.policy.initial_workers {
            return Err(ConfigSchemaError::ValidationError(format!(
                "canister '{role}' scaling pool '{pool_name}' has max_workers < initial_workers",
            )));
        }

        if pool.policy.max_workers == 0 {
            return Err(ConfigSchemaError::ValidationError(format!(
                "Component '{role}' scaling pool '{pool_name}' max_workers must be > 0",
            )));
        }

        let maximum_instances_per_parent = spawn_limit(cfg, role, &pool.canister_role)?;
        if pool.policy.max_workers > maximum_instances_per_parent {
            return Err(ConfigSchemaError::ValidationError(format!(
                "Component '{role}' scaling pool '{pool_name}' max_workers exceeds spawn grant to '{}' maximum_instances_per_parent",
                pool.canister_role,
            )));
        }
    }

    Ok(())
}

fn validate_index(
    cfg: &ComponentSpecConfig,
    role: &CanisterRole,
    canister: &CanisterConfig,
) -> Result<(), ConfigSchemaError> {
    let Some(index) = &canister.index else {
        return Ok(());
    };

    for (pool_name, pool) in &index.pools {
        if pool_name.len() > NAME_MAX_BYTES {
            return Err(ConfigSchemaError::ValidationError(format!(
                "canister '{role}' index pool '{pool_name}' name exceeds {NAME_MAX_BYTES} bytes",
            )));
        }

        if pool.key_name.is_empty() {
            return Err(ConfigSchemaError::ValidationError(format!(
                "canister '{role}' index pool '{pool_name}' must define a non-empty key_name",
            )));
        }

        if pool.key_name.len() > NAME_MAX_BYTES {
            return Err(ConfigSchemaError::ValidationError(format!(
                "canister '{role}' index pool '{pool_name}' key_name '{}' exceeds {NAME_MAX_BYTES} bytes",
                pool.key_name
            )));
        }

        if !cfg.children.contains_key(&pool.canister_role) {
            return Err(ConfigSchemaError::ValidationError(format!(
                "Component '{role}' index pool '{pool_name}' references undeclared child role '{}'",
                pool.canister_role
            )));
        }

        let target = &cfg.children[&pool.canister_role];
        if target.kind != ComponentChildKind::Instance {
            return Err(ConfigSchemaError::ValidationError(format!(
                "Component '{role}' index pool '{pool_name}' references child '{}' which is not kind = \"instance\"",
                pool.canister_role
            )));
        }
        let _ = spawn_limit(cfg, role, &pool.canister_role)?;
    }

    Ok(())
}