canic-core 0.27.7

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
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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
use crate::{
    cdk::{
        candid::Principal,
        types::{Cycles, TC},
    },
    ids::CanisterRole,
};
use serde::{Deserialize, Serialize};
use std::{
    collections::{BTreeMap, BTreeSet},
    fmt,
};

#[cfg(any(not(target_arch = "wasm32"), test))]
use crate::config::schema::{ConfigSchemaError, NAME_MAX_BYTES, Validate};

mod defaults {
    use super::Cycles;

    pub const fn initial_cycles() -> Cycles {
        Cycles::new(5_000_000_000_000)
    }
}

const IMPLICIT_WASM_STORE_ROLE: CanisterRole = CanisterRole::WASM_STORE;

#[cfg(any(not(target_arch = "wasm32"), test))]
fn validate_role_len(role: &CanisterRole, context: &str) -> Result<(), ConfigSchemaError> {
    if role.as_ref().len() > NAME_MAX_BYTES {
        return Err(ConfigSchemaError::ValidationError(format!(
            "{context} '{role}' exceeds {NAME_MAX_BYTES} bytes",
        )));
    }

    Ok(())
}

///
/// SubnetConfig
///

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct SubnetConfig {
    #[serde(default)]
    pub canisters: BTreeMap<CanisterRole, CanisterConfig>,

    #[serde(default)]
    pub auto_create: BTreeSet<CanisterRole>,

    #[serde(default, alias = "subnet_directory")]
    pub subnet_index: BTreeSet<CanisterRole>,

    #[serde(default)]
    pub pool: CanisterPool,
}

impl SubnetConfig {
    /// Get a canister configuration by role.
    #[must_use]
    pub fn get_canister(&self, role: &CanisterRole) -> Option<CanisterConfig> {
        self.canisters.get(role).cloned().or_else(|| {
            if *role == IMPLICIT_WASM_STORE_ROLE {
                Some(implicit_wasm_store_canister_config())
            } else {
                None
            }
        })
    }
}

#[cfg(any(not(target_arch = "wasm32"), test))]
impl Validate for SubnetConfig {
    fn validate(&self) -> Result<(), ConfigSchemaError> {
        // auto_create must reference defined canisters
        for role in &self.auto_create {
            validate_role_len(role, "auto-create canister")?;
            if !self.canisters.contains_key(role) {
                return Err(ConfigSchemaError::ValidationError(format!(
                    "auto-create canister '{role}' is not defined in subnet",
                )));
            }
        }

        // subnet_index must reference singleton canisters
        for role in &self.subnet_index {
            validate_role_len(role, "subnet index canister")?;
            let cfg = self.canisters.get(role).ok_or_else(|| {
                ConfigSchemaError::ValidationError(format!(
                    "subnet index canister '{role}' is not defined in subnet",
                ))
            })?;

            if cfg.kind != CanisterKind::Singleton {
                return Err(ConfigSchemaError::ValidationError(format!(
                    "subnet index canister '{role}' must have kind = \"singleton\"",
                )));
            }
        }

        if self.canisters.contains_key(&IMPLICIT_WASM_STORE_ROLE) {
            return Err(ConfigSchemaError::ValidationError(format!(
                "{} is implicit and must not be configured under subnets.<name>.canisters",
                CanisterRole::WASM_STORE
            )));
        }

        for (role, cfg) in &self.canisters {
            validate_role_len(role, "canister")?;

            if cfg.randomness.enabled && cfg.randomness.reseed_interval_secs == 0 {
                return Err(ConfigSchemaError::ValidationError(format!(
                    "canister '{role}' randomness reseed_interval_secs must be > 0",
                )));
            }

            cfg.validate_kind(role)?;
            cfg.validate_topup_policy(role)?;
            cfg.validate_scaling(role, &self.canisters)?;
            cfg.validate_sharding(role, &self.canisters)?;
            cfg.validate_directory(role, &self.canisters)?;
        }

        Ok(())
    }
}

///
/// PoolImport
/// Per-environment import lists for canister pools.
///

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PoolImport {
    /// Optional count of canisters to import immediately before queuing the rest.
    #[serde(default)]
    pub initial: Option<u16>,

    #[serde(default)]
    pub local: Vec<Principal>,

    #[serde(default)]
    pub ic: Vec<Principal>,
}

///
/// CanisterPool
/// defaults to a minimum size of 0
///

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct CanisterPool {
    pub minimum_size: u8,
    #[serde(default)]
    pub import: PoolImport,
}

///
/// CanisterConfig
///

///
/// DelegatedAuthCanisterConfig
///

// Build the implicit canister configuration for the mandatory store role.
fn implicit_wasm_store_canister_config() -> CanisterConfig {
    CanisterConfig {
        kind: CanisterKind::Singleton,
        initial_cycles: defaults::initial_cycles(),
        topup_policy: None,
        randomness: RandomnessConfig::default(),
        scaling: None,
        sharding: None,
        directory: None,
        delegated_auth: DelegatedAuthCanisterConfig::default(),
        standards: StandardsCanisterConfig::default(),
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct DelegatedAuthCanisterConfig {
    #[serde(default)]
    pub signer: bool,

    #[serde(default)]
    pub verifier: bool,
}

///
/// StandardsCanisterConfig
///

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct StandardsCanisterConfig {
    #[serde(default)]
    pub icrc21: bool,
}

///
/// CanisterConfig
///

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct CanisterConfig {
    /// Kind and placement semantics for this canister role.
    pub kind: CanisterKind,

    #[serde(
        default = "defaults::initial_cycles",
        deserialize_with = "Cycles::from_config"
    )]
    pub initial_cycles: Cycles,

    #[serde(default)]
    pub topup_policy: Option<TopupPolicy>,

    #[serde(default)]
    pub randomness: RandomnessConfig,

    #[serde(default)]
    pub scaling: Option<ScalingConfig>,

    #[serde(default)]
    pub sharding: Option<ShardingConfig>,

    #[serde(default)]
    pub directory: Option<DirectoryConfig>,

    #[serde(default)]
    pub delegated_auth: DelegatedAuthCanisterConfig,

    #[serde(default)]
    pub standards: StandardsCanisterConfig,
}

impl CanisterConfig {
    // Enforce top-up bounds at config load time to avoid runaway refill cascades.
    #[cfg(any(not(target_arch = "wasm32"), test))]
    fn validate_topup_policy(&self, canister: &CanisterRole) -> Result<(), ConfigSchemaError> {
        let Some(topup_policy) = &self.topup_policy else {
            return Ok(());
        };

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

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

        Ok(())
    }

    #[cfg(any(not(target_arch = "wasm32"), test))]
    fn validate_kind(&self, canister: &CanisterRole) -> Result<(), ConfigSchemaError> {
        match self.kind {
            CanisterKind::Root => {
                if self.scaling.is_some()
                    || self.sharding.is_some()
                    || self.directory.is_some()
                    || self.delegated_auth.signer
                    || self.delegated_auth.verifier
                    || self.standards.icrc21
                {
                    return Err(ConfigSchemaError::ValidationError(format!(
                        "canister '{canister}' kind = \"root\" cannot define scaling, sharding, directory, delegated auth roles, or canister-local standards",
                    )));
                }
            }

            CanisterKind::Singleton => {
                // Singletons are the only canisters allowed to define scaling, sharding, and/or directory
            }

            CanisterKind::Replica | CanisterKind::Shard | CanisterKind::Instance => {
                if self.scaling.is_some() || self.sharding.is_some() || self.directory.is_some() {
                    return Err(ConfigSchemaError::ValidationError(format!(
                        "canister '{canister}' kind = \"{}\" cannot define scaling, sharding, or directory",
                        self.kind,
                    )));
                }
            }
        }

        Ok(())
    }

    #[cfg(any(not(target_arch = "wasm32"), test))]
    fn validate_sharding(
        &self,
        role: &CanisterRole,
        all_roles: &BTreeMap<CanisterRole, Self>,
    ) -> Result<(), ConfigSchemaError> {
        let Some(sharding) = &self.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 !all_roles.contains_key(&pool.canister_role) {
                return Err(ConfigSchemaError::ValidationError(format!(
                    "canister '{role}' sharding pool '{pool_name}' references unknown canister role '{}'",
                    pool.canister_role
                )));
            }

            let target = &all_roles[&pool.canister_role];
            if target.kind != CanisterKind::Shard {
                return Err(ConfigSchemaError::ValidationError(format!(
                    "canister '{role}' sharding pool '{pool_name}' references canister '{}' 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",
                )));
            }
        }

        Ok(())
    }

    #[cfg(any(not(target_arch = "wasm32"), test))]
    fn validate_scaling(
        &self,
        role: &CanisterRole,
        all_roles: &BTreeMap<CanisterRole, Self>,
    ) -> Result<(), ConfigSchemaError> {
        let Some(scaling) = &self.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 !all_roles.contains_key(&pool.canister_role) {
                return Err(ConfigSchemaError::ValidationError(format!(
                    "canister '{role}' scaling pool '{pool_name}' references unknown canister role '{}'",
                    pool.canister_role
                )));
            }

            let target = &all_roles[&pool.canister_role];
            if target.kind != CanisterKind::Replica {
                return Err(ConfigSchemaError::ValidationError(format!(
                    "canister '{role}' scaling pool '{pool_name}' references canister '{}' 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",
                )));
            }
        }

        Ok(())
    }

    // Validate keyed instance-placement pools for singleton directory parents.
    #[cfg(any(not(target_arch = "wasm32"), test))]
    fn validate_directory(
        &self,
        role: &CanisterRole,
        all_roles: &BTreeMap<CanisterRole, Self>,
    ) -> Result<(), ConfigSchemaError> {
        let Some(directory) = &self.directory else {
            return Ok(());
        };

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

            if pool.key_name.is_empty() {
                return Err(ConfigSchemaError::ValidationError(format!(
                    "canister '{role}' directory 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}' directory pool '{pool_name}' key_name '{}' exceeds {NAME_MAX_BYTES} bytes",
                    pool.key_name
                )));
            }

            if !all_roles.contains_key(&pool.canister_role) {
                return Err(ConfigSchemaError::ValidationError(format!(
                    "canister '{role}' directory pool '{pool_name}' references unknown canister role '{}'",
                    pool.canister_role
                )));
            }

            let target = &all_roles[&pool.canister_role];
            if target.kind != CanisterKind::Instance {
                return Err(ConfigSchemaError::ValidationError(format!(
                    "canister '{role}' directory pool '{pool_name}' references canister '{}' which is not kind = \"instance\"",
                    pool.canister_role
                )));
            }
        }

        Ok(())
    }
}

///
/// CanisterKind
/// Kind semantics for canister roles within the topology.
///
/// Do not encode parent relationships here; this is role-level intent only.
///

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CanisterKind {
    Root,
    Singleton,
    Replica,
    Shard,
    Instance,
}

impl fmt::Display for CanisterKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let label = match self {
            Self::Root => "root",
            Self::Singleton => "singleton",
            Self::Replica => "replica",
            Self::Shard => "shard",
            Self::Instance => "instance",
        };

        f.write_str(label)
    }
}

///
/// TopupPolicy
///

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct TopupPolicy {
    #[serde(default, deserialize_with = "Cycles::from_config")]
    pub threshold: Cycles,

    #[serde(default, deserialize_with = "Cycles::from_config")]
    pub amount: Cycles,
}

impl Default for TopupPolicy {
    fn default() -> Self {
        Self {
            threshold: Cycles::new(10 * TC),
            amount: Cycles::new(4 * TC),
        }
    }
}

///
/// RandomnessConfig
///

#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields, default)]
pub struct RandomnessConfig {
    pub enabled: bool,
    pub reseed_interval_secs: u64,
    pub source: RandomnessSource,
}

impl Default for RandomnessConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            reseed_interval_secs: 3600,
            source: RandomnessSource::Ic,
        }
    }
}

///
/// RandomnessSource
///

#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RandomnessSource {
    #[default]
    Ic,
    Time,
}

///
/// ScalingConfig
/// (stateless, scaling)
///
/// * Organizes canisters into **replica groups** (e.g. "oracle").
/// * Replicas are interchangeable and handle transient tasks (no stable instance assignment).
/// * Scaling is about throughput, not capacity.
/// * Hence: `ReplicaManager → pools → ReplicaSpec → ReplicaPolicy`.
///

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ScalingConfig {
    #[serde(default)]
    pub pools: BTreeMap<String, ScalePool>,
}

///
/// ScalePool
/// One stateless replica group (e.g. "oracle").
///

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ScalePool {
    pub canister_role: CanisterRole,

    #[serde(default)]
    pub policy: ScalePoolPolicy,
}

///
/// ScalePoolPolicy
///

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields, default)]
pub struct ScalePoolPolicy {
    /// Minimum number of replica canisters to keep alive
    pub min_workers: u32,

    /// Maximum number of replica canisters to allow
    pub max_workers: u32,
}

impl Default for ScalePoolPolicy {
    fn default() -> Self {
        Self {
            min_workers: 1,
            max_workers: 32,
        }
    }
}

///
/// ShardingConfig
/// (stateful, partitioned)
///
/// * Organizes canisters into named **pools**.
/// * Each pool manages a set of **shards**, and each shard owns a partition of state.
/// * Stable logical keys are assigned to shards via HRW and stay there.
/// * Hence: `ShardManager → pools → ShardPoolSpec → ShardPoolPolicy`.
///

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ShardingConfig {
    #[serde(default)]
    pub pools: BTreeMap<String, ShardPool>,
}

///
/// DirectoryConfig
/// (keyed instance placement)
///
/// * Organizes canisters into named **pools**.
/// * Each pool maps one configured key name to at most one dedicated instance root.
/// * The resolved instance identity is stable and usually owns a recursive subtree.
/// * Hence: `DirectoryManager → pools → DirectoryPool`.
///

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct DirectoryConfig {
    #[serde(default)]
    pub pools: BTreeMap<String, DirectoryPool>,
}

///
/// DirectoryPool
///

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct DirectoryPool {
    pub canister_role: CanisterRole,
    pub key_name: String,
}

///
/// ShardPool
///

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ShardPool {
    pub canister_role: CanisterRole,

    #[serde(default)]
    pub policy: ShardPoolPolicy,
}

///
/// ShardPoolPolicy
///

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields, default)]
pub struct ShardPoolPolicy {
    pub capacity: u32,
    pub max_shards: u32,
}

impl Default for ShardPoolPolicy {
    fn default() -> Self {
        Self {
            capacity: 1_000,
            max_shards: 4,
        }
    }
}

///
/// TESTS
///

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::{BTreeMap, BTreeSet};

    fn base_canister_config(kind: CanisterKind) -> CanisterConfig {
        CanisterConfig {
            kind,
            initial_cycles: defaults::initial_cycles(),
            topup_policy: None,
            randomness: RandomnessConfig::default(),
            scaling: None,
            sharding: None,
            directory: None,
            delegated_auth: DelegatedAuthCanisterConfig::default(),
            standards: StandardsCanisterConfig::default(),
        }
    }

    #[test]
    fn randomness_defaults_to_ic() {
        let cfg = RandomnessConfig::default();

        assert!(cfg.enabled);
        assert_eq!(cfg.reseed_interval_secs, 3600);
        assert_eq!(cfg.source, RandomnessSource::Ic);
    }

    #[test]
    fn randomness_source_parses_ic_and_time() {
        let cfg: RandomnessConfig = toml::from_str("source = \"ic\"").unwrap();
        assert_eq!(cfg.source, RandomnessSource::Ic);

        let cfg: RandomnessConfig = toml::from_str("source = \"time\"").unwrap();
        assert_eq!(cfg.source, RandomnessSource::Time);
    }

    #[test]
    fn auto_create_entries_must_exist_in_subnet() {
        let mut auto_create = BTreeSet::new();
        auto_create.insert(CanisterRole::from("missing_auto_canister"));

        let subnet = SubnetConfig {
            auto_create,
            ..Default::default()
        };

        subnet
            .validate()
            .expect_err("expected missing auto-create role to fail");
    }

    #[test]
    fn sharding_pool_references_must_exist_in_subnet() {
        let managing_role: CanisterRole = "shard_hub".into();
        let mut canisters = BTreeMap::new();

        let mut sharding = ShardingConfig::default();
        sharding.pools.insert(
            "primary".into(),
            ShardPool {
                canister_role: CanisterRole::from("missing_shard_worker"),
                policy: ShardPoolPolicy::default(),
            },
        );

        let manager_cfg = CanisterConfig {
            sharding: Some(sharding),
            ..base_canister_config(CanisterKind::Shard)
        };

        canisters.insert(managing_role, manager_cfg);

        let subnet = SubnetConfig {
            canisters,
            ..Default::default()
        };

        subnet
            .validate()
            .expect_err("expected missing replica role to fail");
    }

    #[test]
    fn sharding_pool_policy_requires_positive_capacity_and_shards() {
        let managing_role: CanisterRole = "shard_hub".into();
        let mut canisters = BTreeMap::new();

        let mut sharding = ShardingConfig::default();
        sharding.pools.insert(
            "primary".into(),
            ShardPool {
                canister_role: managing_role.clone(),
                policy: ShardPoolPolicy {
                    capacity: 0,
                    max_shards: 0,
                },
            },
        );

        canisters.insert(
            managing_role,
            CanisterConfig {
                sharding: Some(sharding),
                ..base_canister_config(CanisterKind::Shard)
            },
        );

        let subnet = SubnetConfig {
            canisters,
            ..Default::default()
        };

        subnet
            .validate()
            .expect_err("expected invalid sharding policy to fail");
    }

    #[test]
    fn canister_role_name_must_fit_bound() {
        let long_role = "a".repeat(NAME_MAX_BYTES + 1);
        let mut canisters = BTreeMap::new();
        canisters.insert(
            CanisterRole::from(long_role),
            base_canister_config(CanisterKind::Singleton),
        );

        let subnet = SubnetConfig {
            canisters,
            ..Default::default()
        };

        subnet
            .validate()
            .expect_err("expected canister role length to fail");
    }

    #[test]
    fn sharding_pool_name_must_fit_bound() {
        let managing_role: CanisterRole = "shard_hub".into();
        let mut canisters = BTreeMap::new();

        let mut sharding = ShardingConfig::default();
        sharding.pools.insert(
            "a".repeat(NAME_MAX_BYTES + 1),
            ShardPool {
                canister_role: managing_role.clone(),
                policy: ShardPoolPolicy::default(),
            },
        );

        canisters.insert(
            managing_role,
            CanisterConfig {
                sharding: Some(sharding),
                ..base_canister_config(CanisterKind::Shard)
            },
        );

        let subnet = SubnetConfig {
            canisters,
            ..Default::default()
        };

        subnet
            .validate()
            .expect_err("expected sharding pool name length to fail");
    }

    #[test]
    fn scaling_pool_policy_requires_max_ge_min_when_bounded() {
        let mut canisters = BTreeMap::new();
        let mut pools = BTreeMap::new();
        pools.insert(
            "replica".into(),
            ScalePool {
                canister_role: CanisterRole::from("replica"),
                policy: ScalePoolPolicy {
                    min_workers: 5,
                    max_workers: 3,
                },
            },
        );

        canisters.insert(
            CanisterRole::from("replica"),
            base_canister_config(CanisterKind::Replica),
        );

        let manager_cfg = CanisterConfig {
            scaling: Some(ScalingConfig { pools }),
            ..base_canister_config(CanisterKind::Singleton)
        };

        canisters.insert(CanisterRole::from("manager"), manager_cfg);

        let subnet = SubnetConfig {
            canisters,
            ..Default::default()
        };

        subnet
            .validate()
            .expect_err("expected invalid scaling policy to fail");
    }

    #[test]
    fn scaling_pool_name_must_fit_bound() {
        let mut canisters = BTreeMap::new();
        let mut pools = BTreeMap::new();
        pools.insert(
            "a".repeat(NAME_MAX_BYTES + 1),
            ScalePool {
                canister_role: CanisterRole::from("replica"),
                policy: ScalePoolPolicy::default(),
            },
        );

        canisters.insert(
            CanisterRole::from("replica"),
            base_canister_config(CanisterKind::Replica),
        );

        let manager_cfg = CanisterConfig {
            scaling: Some(ScalingConfig { pools }),
            ..base_canister_config(CanisterKind::Singleton)
        };

        canisters.insert(CanisterRole::from("manager"), manager_cfg);

        let subnet = SubnetConfig {
            canisters,
            ..Default::default()
        };

        subnet
            .validate()
            .expect_err("expected scaling pool name length to fail");
    }

    #[test]
    fn directory_pool_references_must_exist_in_subnet() {
        let managing_role: CanisterRole = "project_hub".into();
        let mut canisters = BTreeMap::new();

        let mut directory = DirectoryConfig::default();
        directory.pools.insert(
            "projects".into(),
            DirectoryPool {
                canister_role: CanisterRole::from("missing_project_instance"),
                key_name: "project".into(),
            },
        );

        let manager_cfg = CanisterConfig {
            directory: Some(directory),
            ..base_canister_config(CanisterKind::Singleton)
        };

        canisters.insert(managing_role, manager_cfg);

        let subnet = SubnetConfig {
            canisters,
            ..Default::default()
        };

        subnet
            .validate()
            .expect_err("expected missing directory target role to fail");
    }

    #[test]
    fn directory_pool_target_must_be_instance_kind() {
        let managing_role: CanisterRole = "project_hub".into();
        let mut canisters = BTreeMap::new();

        let mut directory = DirectoryConfig::default();
        directory.pools.insert(
            "projects".into(),
            DirectoryPool {
                canister_role: CanisterRole::from("project_instance"),
                key_name: "project".into(),
            },
        );

        canisters.insert(
            CanisterRole::from("project_instance"),
            base_canister_config(CanisterKind::Singleton),
        );
        canisters.insert(
            managing_role,
            CanisterConfig {
                directory: Some(directory),
                ..base_canister_config(CanisterKind::Singleton)
            },
        );

        let subnet = SubnetConfig {
            canisters,
            ..Default::default()
        };

        subnet
            .validate()
            .expect_err("expected non-instance directory target role to fail");
    }

    #[test]
    fn directory_pool_requires_non_empty_key_name() {
        let managing_role: CanisterRole = "project_hub".into();
        let mut canisters = BTreeMap::new();

        let mut directory = DirectoryConfig::default();
        directory.pools.insert(
            "projects".into(),
            DirectoryPool {
                canister_role: CanisterRole::from("project_instance"),
                key_name: String::new(),
            },
        );

        canisters.insert(
            CanisterRole::from("project_instance"),
            base_canister_config(CanisterKind::Instance),
        );
        canisters.insert(
            managing_role,
            CanisterConfig {
                directory: Some(directory),
                ..base_canister_config(CanisterKind::Singleton)
            },
        );

        let subnet = SubnetConfig {
            canisters,
            ..Default::default()
        };

        subnet
            .validate()
            .expect_err("expected empty directory key name to fail");
    }

    #[test]
    fn randomness_interval_requires_positive_value() {
        let mut canisters = BTreeMap::new();

        let cfg = CanisterConfig {
            randomness: RandomnessConfig {
                enabled: true,
                reseed_interval_secs: 0,
                ..Default::default()
            },
            ..base_canister_config(CanisterKind::Singleton)
        };

        canisters.insert(CanisterRole::from("app"), cfg);

        let subnet = SubnetConfig {
            canisters,
            ..Default::default()
        };

        subnet
            .validate()
            .expect_err("expected invalid randomness interval to fail");
    }

    #[test]
    fn wasm_store_canister_config_is_implicit() {
        let subnet = SubnetConfig::default();
        let cfg = subnet
            .get_canister(&CanisterRole::WASM_STORE)
            .expect("expected implicit wasm_store canister");

        assert_eq!(cfg.kind, CanisterKind::Singleton);
        assert_eq!(cfg.initial_cycles, defaults::initial_cycles());
    }

    #[test]
    fn explicit_wasm_store_canister_config_is_rejected() {
        let mut canisters = BTreeMap::new();
        canisters.insert(
            CanisterRole::WASM_STORE,
            base_canister_config(CanisterKind::Singleton),
        );

        let subnet = SubnetConfig {
            canisters,
            ..Default::default()
        };

        subnet
            .validate()
            .expect_err("expected explicit wasm_store config to fail");
    }

    #[test]
    fn topup_policy_amount_above_half_threshold_fails() {
        let mut canisters = BTreeMap::new();

        let cfg = CanisterConfig {
            topup_policy: Some(TopupPolicy {
                threshold: Cycles::new(10 * TC),
                amount: Cycles::new(6 * TC),
            }),
            ..base_canister_config(CanisterKind::Singleton)
        };

        canisters.insert(CanisterRole::from("app"), cfg);

        let subnet = SubnetConfig {
            canisters,
            ..Default::default()
        };

        subnet
            .validate()
            .expect_err("expected topup_policy amount above half threshold to fail");
    }

    #[test]
    fn topup_policy_amount_equal_half_threshold_is_valid() {
        let mut canisters = BTreeMap::new();

        let cfg = CanisterConfig {
            topup_policy: Some(TopupPolicy {
                threshold: Cycles::new(50 * TC),
                amount: Cycles::new(25 * TC),
            }),
            ..base_canister_config(CanisterKind::Singleton)
        };

        canisters.insert(CanisterRole::from("app"), cfg);

        let subnet = SubnetConfig {
            canisters,
            ..Default::default()
        };

        subnet
            .validate()
            .expect("expected topup_policy amount equal to half threshold to validate");
    }

    #[test]
    fn topup_policy_amount_below_half_threshold_is_valid() {
        let mut canisters = BTreeMap::new();

        let cfg = CanisterConfig {
            topup_policy: Some(TopupPolicy {
                threshold: Cycles::new(10 * TC),
                amount: Cycles::new(4 * TC),
            }),
            ..base_canister_config(CanisterKind::Singleton)
        };

        canisters.insert(CanisterRole::from("app"), cfg);

        let subnet = SubnetConfig {
            canisters,
            ..Default::default()
        };

        subnet
            .validate()
            .expect("expected topup_policy amount below half threshold to validate");
    }

    #[test]
    fn default_topup_policy_is_below_half_threshold() {
        let mut canisters = BTreeMap::new();

        let cfg = CanisterConfig {
            topup_policy: Some(TopupPolicy::default()),
            ..base_canister_config(CanisterKind::Singleton)
        };

        canisters.insert(CanisterRole::from("app"), cfg);

        let subnet = SubnetConfig {
            canisters,
            ..Default::default()
        };

        subnet
            .validate()
            .expect("expected default topup_policy to satisfy half-threshold invariant");
    }

    #[test]
    fn shard_kind_allows_missing_sharding_config() {
        let mut canisters = BTreeMap::new();
        canisters.insert(
            CanisterRole::from("shard"),
            base_canister_config(CanisterKind::Shard),
        );

        let subnet = SubnetConfig {
            canisters,
            ..Default::default()
        };

        subnet
            .validate()
            .expect("expected shard config without sharding to validate");
    }

    #[test]
    fn explicit_canister_role_is_rejected() {
        toml::from_str::<SubnetConfig>(
            r#"
[canisters.app]
role = "app"
kind = "singleton"
"#,
        )
        .expect_err("expected explicit role to fail validation");
    }

    #[test]
    fn explicit_canister_type_is_rejected() {
        toml::from_str::<SubnetConfig>(
            r#"
[canisters.app]
kind = "singleton"
type = "singleton"
"#,
        )
        .expect_err("expected explicit type to fail validation");
    }

    #[test]
    fn explicit_sharding_role_is_rejected() {
        toml::from_str::<SubnetConfig>(
            r#"
[canisters.manager]
kind = "singleton"

[canisters.manager.sharding]
role = "shard"
"#,
        )
        .expect_err("expected explicit sharding role to fail validation");
    }

    #[test]
    fn instance_kind_parses() {
        let subnet = toml::from_str::<SubnetConfig>(
            r#"
[canisters.instance_role]
kind = "instance"
"#,
        )
        .expect("expected instance kind to parse");

        let cfg = subnet
            .canisters
            .get(&CanisterRole::from("instance_role"))
            .expect("instance role config should exist");
        assert_eq!(cfg.kind, CanisterKind::Instance);
    }

    #[test]
    fn legacy_node_kind_is_rejected() {
        toml::from_str::<SubnetConfig>(
            r#"
[canisters.app]
kind = "node"
"#,
        )
        .expect_err("expected legacy node kind to fail parsing");
    }

    #[test]
    fn legacy_worker_kind_is_rejected() {
        toml::from_str::<SubnetConfig>(
            r#"
[canisters.app]
kind = "worker"
"#,
        )
        .expect_err("expected legacy worker kind to fail parsing");
    }
}