ic-query 0.22.1

Internet Computer query library for NNS, SNS, ICRC, system canisters, and public network metadata
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
//! Module: ic::model
//!
//! Responsibility: public IC Dashboard requests, source data, reports, and errors.
//! Does not own: HTTP transport, source validation, report assembly, or rendering.
//! Boundary: preserves raw Dashboard values and explicit off-chain provenance.

#[cfg(feature = "host")]
use crate::runtime::RuntimeError;
use serde::Serialize;
use std::{fmt, str::FromStr};
#[cfg(feature = "host")]
use thiserror::Error as ThisError;

///
/// IcMetricKind
///
/// One bounded network metric exposed by the official Dashboard Metrics API.
///

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum IcMetricKind {
    /// Network instruction execution rate.
    InstructionRate,
    /// Network message execution rate.
    MessageExecutionRate,
    /// Network cycle burn rate.
    CycleBurnRate,
    /// Network block ingestion rate.
    BlockRate,
    /// Total and currently up node counts.
    IcNodeCount,
    /// Total Subnet count.
    IcSubnetTotal,
    /// Running and stopped canister counts.
    RegisteredCanistersCount,
    /// Total estimated IC energy-consumption rate in kWh.
    TotalIcEnergyConsumptionRateKwh,
    /// Active boundary-node count.
    BoundaryNodesCount,
}

impl IcMetricKind {
    /// Return every metric supported by the bounded report adapter.
    #[must_use]
    pub const fn all() -> [Self; 9] {
        [
            Self::InstructionRate,
            Self::MessageExecutionRate,
            Self::CycleBurnRate,
            Self::BlockRate,
            Self::IcNodeCount,
            Self::IcSubnetTotal,
            Self::RegisteredCanistersCount,
            Self::TotalIcEnergyConsumptionRateKwh,
            Self::BoundaryNodesCount,
        ]
    }

    /// Return the official Dashboard Metrics API path name.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::InstructionRate => "instruction-rate",
            Self::MessageExecutionRate => "message-execution-rate",
            Self::CycleBurnRate => "cycle-burn-rate",
            Self::BlockRate => "block-rate",
            Self::IcNodeCount => "ic-node-count",
            Self::IcSubnetTotal => "ic-subnet-total",
            Self::RegisteredCanistersCount => "registered-canisters-count",
            Self::TotalIcEnergyConsumptionRateKwh => "total-ic-energy-consumption-rate-kwh",
            Self::BoundaryNodesCount => "boundary-nodes-count",
        }
    }

    #[cfg(feature = "host")]
    pub(crate) const fn series_names(self) -> &'static [&'static str] {
        match self {
            Self::InstructionRate => &["instruction_rate"],
            Self::MessageExecutionRate => &["message_execution_rate"],
            Self::CycleBurnRate => &["cycle_burn_rate"],
            Self::BlockRate => &["block_rate"],
            Self::IcNodeCount => &["total_nodes", "up_nodes"],
            Self::IcSubnetTotal => &["ic_subnet_total"],
            Self::RegisteredCanistersCount => &["running_canisters", "stopped_canisters"],
            Self::TotalIcEnergyConsumptionRateKwh => &["energy_consumption_rate"],
            Self::BoundaryNodesCount => &["boundary_nodes_count"],
        }
    }
}

impl fmt::Display for IcMetricKind {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for IcMetricKind {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::all()
            .into_iter()
            .find(|metric| metric.as_str() == value)
            .ok_or_else(|| format!("unsupported IC Dashboard metric {value:?}"))
    }
}

///
/// IcMetricQuery
///
/// One explicitly bounded official Dashboard metric time-series query.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcMetricQuery {
    /// Official Dashboard metric to retrieve.
    pub metric: IcMetricKind,
    /// Inclusive query start as Unix seconds.
    pub start_unix_secs: u64,
    /// Inclusive query end as Unix seconds.
    pub end_unix_secs: u64,
    /// Requested observation interval in seconds.
    pub step_secs: u32,
}

impl IcMetricQuery {
    /// Construct one explicit metric query window.
    #[must_use]
    pub const fn new(
        metric: IcMetricKind,
        start_unix_secs: u64,
        end_unix_secs: u64,
        step_secs: u32,
    ) -> Self {
        Self {
            metric,
            start_unix_secs,
            end_unix_secs,
            step_secs,
        }
    }
}

///
/// IcMetricRequest
///
/// Request accepted by the bounded official Dashboard metric report builder.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcMetricRequest {
    /// Dashboard Metrics API base endpoint.
    pub source_endpoint: String,
    /// Collection time as Unix seconds.
    pub now_unix_secs: u64,
    /// Explicitly bounded metric query.
    pub query: IcMetricQuery,
}

impl IcMetricRequest {
    /// Construct one bounded live Dashboard metric request.
    #[must_use]
    pub fn new(
        source_endpoint: impl Into<String>,
        now_unix_secs: u64,
        query: IcMetricQuery,
    ) -> Self {
        Self {
            source_endpoint: source_endpoint.into(),
            now_unix_secs,
            query,
        }
    }
}

///
/// IcDailyStatsQuery
///
/// One explicitly bounded official Dashboard daily-statistics query.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcDailyStatsQuery {
    /// Inclusive query start as Unix seconds.
    pub start_unix_secs: u64,
    /// Inclusive query end as Unix seconds.
    pub end_unix_secs: u64,
}

impl IcDailyStatsQuery {
    /// Construct one explicit daily-statistics query window.
    #[must_use]
    pub const fn new(start_unix_secs: u64, end_unix_secs: u64) -> Self {
        Self {
            start_unix_secs,
            end_unix_secs,
        }
    }
}

///
/// IcDailyStatsRequest
///
/// Request accepted by the bounded official Dashboard daily-statistics builder.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcDailyStatsRequest {
    /// Dashboard API v3 base endpoint.
    pub source_endpoint: String,
    /// Collection time as Unix seconds.
    pub now_unix_secs: u64,
    /// Explicitly bounded daily-statistics query.
    pub query: IcDailyStatsQuery,
}

impl IcDailyStatsRequest {
    /// Construct one bounded live Dashboard daily-statistics request.
    #[must_use]
    pub fn new(
        source_endpoint: impl Into<String>,
        now_unix_secs: u64,
        query: IcDailyStatsQuery,
    ) -> Self {
        Self {
            source_endpoint: source_endpoint.into(),
            now_unix_secs,
            query,
        }
    }
}

///
/// IcBoundaryNodeDataCentersRequest
///
/// Request accepted by the official Dashboard boundary-node data-center builder.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcBoundaryNodeDataCentersRequest {
    /// Dashboard API v4 base endpoint.
    pub source_endpoint: String,
    /// Collection time as Unix seconds.
    pub now_unix_secs: u64,
}

impl IcBoundaryNodeDataCentersRequest {
    /// Construct one live Dashboard boundary-node data-center request.
    #[must_use]
    pub fn new(source_endpoint: impl Into<String>, now_unix_secs: u64) -> Self {
        Self {
            source_endpoint: source_endpoint.into(),
            now_unix_secs,
        }
    }
}

///
/// IcCanisterRequest
///
/// Request accepted by the official Dashboard canister report builder.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcCanisterRequest {
    /// Dashboard API base endpoint.
    pub source_endpoint: String,
    /// Collection time as Unix seconds.
    pub now_unix_secs: u64,
    /// Canister principal to inspect.
    pub canister_id: String,
}

impl IcCanisterRequest {
    /// Construct a live Dashboard canister request.
    #[must_use]
    pub fn new(
        source_endpoint: impl Into<String>,
        now_unix_secs: u64,
        canister_id: impl Into<String>,
    ) -> Self {
        Self {
            source_endpoint: source_endpoint.into(),
            now_unix_secs,
            canister_id: canister_id.into(),
        }
    }
}

///
/// IcCanisterFilters
///
/// Official Dashboard filters shared by canister count and page requests.
///

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
pub struct IcCanisterFilters {
    /// Select canisters according to whether the Dashboard records a name.
    pub has_name: Option<bool>,
    /// Select canisters assigned to this Subnet principal.
    pub subnet_id: Option<String>,
    /// Select canisters controlled by this principal.
    pub controller_id: Option<String>,
    /// Raw Dashboard language labels to include.
    pub languages: Vec<String>,
    /// Raw Dashboard canister classifications to include.
    pub canister_types: Vec<String>,
    /// Raw Dashboard text search, between two and one hundred characters.
    pub query: Option<String>,
}

///
/// IcCanisterCountRequest
///
/// Request for one bounded official Dashboard canister-count lookup.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcCanisterCountRequest {
    /// Dashboard API v4 base endpoint.
    pub source_endpoint: String,
    /// Collection time as Unix seconds.
    pub now_unix_secs: u64,
    /// Filters applied by the Dashboard.
    pub filters: IcCanisterFilters,
}

impl IcCanisterCountRequest {
    /// Construct a live Dashboard canister-count request without filters.
    #[must_use]
    pub fn new(source_endpoint: impl Into<String>, now_unix_secs: u64) -> Self {
        Self {
            source_endpoint: source_endpoint.into(),
            now_unix_secs,
            filters: IcCanisterFilters::default(),
        }
    }

    /// Set the Dashboard filters used by this request.
    #[must_use]
    pub fn with_filters(mut self, filters: IcCanisterFilters) -> Self {
        self.filters = filters;
        self
    }
}

///
/// IcCanisterPageRequest
///
/// Request for one bounded official Dashboard canister page.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcCanisterPageRequest {
    /// Dashboard API v4 base endpoint.
    pub source_endpoint: String,
    /// Collection time as Unix seconds.
    pub now_unix_secs: u64,
    /// Filters applied by the Dashboard.
    pub filters: IcCanisterFilters,
    /// Maximum rows requested from the API.
    pub limit: u16,
    /// Exclusive forward cursor returned by an earlier page.
    pub after: Option<String>,
    /// Exclusive backward cursor returned by an earlier page.
    pub before: Option<String>,
}

impl IcCanisterPageRequest {
    /// Construct a live Dashboard page request with the default bounded limit.
    #[must_use]
    pub fn new(source_endpoint: impl Into<String>, now_unix_secs: u64) -> Self {
        Self {
            source_endpoint: source_endpoint.into(),
            now_unix_secs,
            filters: IcCanisterFilters::default(),
            limit: super::DEFAULT_IC_CANISTER_PAGE_LIMIT,
            after: None,
            before: None,
        }
    }

    /// Set the Dashboard filters used by this request.
    #[must_use]
    pub fn with_filters(mut self, filters: IcCanisterFilters) -> Self {
        self.filters = filters;
        self
    }

    /// Set the maximum number of returned rows.
    #[must_use]
    pub const fn with_limit(mut self, limit: u16) -> Self {
        self.limit = limit;
        self
    }

    /// Set an exclusive forward cursor.
    #[must_use]
    pub fn with_after(mut self, after: impl Into<String>) -> Self {
        self.after = Some(after.into());
        self
    }

    /// Set an exclusive backward cursor.
    #[must_use]
    pub fn with_before(mut self, before: impl Into<String>) -> Self {
        self.before = Some(before.into());
        self
    }
}

///
/// IcCanisterUpgrade
///
/// One proposal-linked canister upgrade recorded by the Dashboard API.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcCanisterUpgrade {
    /// Proposal execution time as raw Unix seconds.
    pub executed_timestamp_seconds: u64,
    /// Wasm module hash as raw lowercase hexadecimal text.
    pub module_hash: String,
    /// NNS proposal that installed this module.
    pub proposal_id: u64,
}

///
/// IcDashboardReportProvenance
///
/// Shared off-chain provenance and authority guarantees for Dashboard reports.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcDashboardReportProvenance {
    /// Report schema version.
    pub schema_version: u32,
    /// Network represented by the official Dashboard API.
    pub network: String,
    /// Authority that supplied the report fields.
    pub authority: String,
    /// Dashboard API base endpoint queried by the source.
    pub source_endpoint: String,
    /// Time this report was collected.
    pub fetched_at: String,
    /// Collector identity.
    pub fetched_by: String,
    /// Whether the API response is cryptographically certified IC state.
    pub certified: bool,
    /// Whether every returned value is guaranteed to describe one point in time.
    pub point_in_time_guaranteed: bool,
}

///
/// IcMetricObservation
///
/// One raw timestamp and value returned by the Dashboard Metrics API.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcMetricObservation {
    /// Observation timestamp as Unix seconds.
    pub timestamp_unix_secs: u64,
    /// Raw value string returned by the Dashboard.
    pub value: String,
}

///
/// IcMetricSeries
///
/// One named raw series in a Dashboard metric response.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcMetricSeries {
    /// Raw Dashboard response field that names this series.
    pub name: String,
    /// Observations in strictly increasing timestamp order.
    pub observations: Vec<IcMetricObservation>,
}

///
/// IcMetricReport
///
/// One bounded time-series response from the official Dashboard Metrics API.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcMetricReport {
    /// Shared Dashboard provenance, flattened in serialized report JSON.
    #[serde(flatten)]
    pub provenance: IcDashboardReportProvenance,
    /// Metric and explicit time-series bounds, flattened in report JSON.
    #[serde(flatten)]
    pub query: IcMetricQuery,
    /// Number of named series returned by the API.
    pub returned_series_count: usize,
    /// Total number of observations across all returned series.
    pub returned_observation_count: usize,
    /// Raw named time series in canonical series-name order.
    pub series: Vec<IcMetricSeries>,
}

///
/// IcDailyStatsRow
///
/// Selected raw daily network-activity values returned by the Dashboard API.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcDailyStatsRow {
    /// Raw UTC calendar day returned by the Dashboard.
    pub day: String,
    /// Observation timestamp as Unix seconds.
    pub timestamp_unix_secs: u64,
    /// Raw average query-transaction rate.
    pub average_query_transactions_per_second: String,
    /// Raw average update-transaction rate.
    pub average_update_transactions_per_second: String,
    /// Raw average total-transaction rate.
    pub average_transactions_per_second: String,
    /// Raw maximum query-transaction rate.
    pub max_query_transactions_per_second: String,
    /// Raw maximum update-transaction rate.
    pub max_update_transactions_per_second: String,
    /// Raw maximum total-transaction rate.
    pub max_total_transactions_per_second: String,
    /// Raw average block-production rate.
    pub blocks_per_second_average: String,
}

///
/// IcDailyStatsReport
///
/// One bounded daily network-activity response from the official Dashboard API.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcDailyStatsReport {
    /// Shared Dashboard provenance, flattened in serialized report JSON.
    #[serde(flatten)]
    pub provenance: IcDashboardReportProvenance,
    /// Exact requested time bounds, flattened in report JSON.
    #[serde(flatten)]
    pub query: IcDailyStatsQuery,
    /// Number of daily rows returned by the API.
    pub returned_day_count: usize,
    /// Rows in strictly increasing timestamp order.
    pub rows: Vec<IcDailyStatsRow>,
}

///
/// IcBoundaryNodeDataCenterRow
///
/// One raw data-center aggregate returned by the boundary-node API.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcBoundaryNodeDataCenterRow {
    /// Dashboard data-center identifier.
    pub dc_id: String,
    /// Raw data-center display name.
    pub name: String,
    /// Raw infrastructure-owner label.
    pub owner: String,
    /// Raw Dashboard region label.
    pub region: String,
    /// Raw decimal latitude.
    pub latitude: String,
    /// Raw decimal longitude.
    pub longitude: String,
    /// Raw decimal count of boundary nodes assigned to this data center.
    pub total_nodes: String,
}

///
/// IcBoundaryNodeDataCentersReport
///
/// One complete response from the official boundary-node data-center resource.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcBoundaryNodeDataCentersReport {
    /// Shared Dashboard provenance, flattened in serialized report JSON.
    #[serde(flatten)]
    pub provenance: IcDashboardReportProvenance,
    /// Number of data-center rows returned by the API.
    pub data_center_count: usize,
    /// Sum of the raw per-data-center boundary-node counts.
    pub total_node_count: u64,
    /// Rows in canonical data-center-id order, including zero-node locations.
    pub rows: Vec<IcBoundaryNodeDataCenterRow>,
}

///
/// IcCanisterReport
///
/// One live canister metadata report from the official Dashboard API.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcCanisterReport {
    /// Shared Dashboard provenance, flattened in serialized report JSON.
    #[serde(flatten)]
    pub provenance: IcDashboardReportProvenance,
    /// Canonical canister principal.
    pub canister_id: String,
    /// Dashboard database row identifier.
    pub dashboard_id: u64,
    /// Raw optional Dashboard canister classification.
    pub canister_type: Option<String>,
    /// Raw Dashboard canister name; an empty string means no name was recorded.
    pub name: String,
    /// Canonical Subnet principal recorded by the Dashboard.
    pub subnet_id: String,
    /// Canonically ordered controller principals recorded by the Dashboard.
    pub controllers: Vec<String>,
    /// Raw Dashboard language label; an empty string means no language was recorded.
    pub language: String,
    /// Raw current module hash; an empty string means no hash was recorded.
    pub module_hash: String,
    /// Raw Dashboard row update timestamp.
    pub dashboard_updated_at: String,
    /// Number of proposal-linked upgrades when history is available.
    pub upgrade_count: Option<usize>,
    /// Proposal-linked upgrade history, or `None` when the Dashboard returned `null`.
    pub upgrades: Option<Vec<IcCanisterUpgrade>>,
}

///
/// IcCanisterCountReport
///
/// One filtered canister count from the official Dashboard API.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcCanisterCountReport {
    /// Shared Dashboard provenance, flattened in serialized report JSON.
    #[serde(flatten)]
    pub provenance: IcDashboardReportProvenance,
    /// Filters applied by the Dashboard.
    pub filters: IcCanisterFilters,
    /// Number of matching Dashboard canister records.
    pub total: u64,
}

///
/// IcCanisterPageController
///
/// One controller entry returned by the Dashboard canister collection API.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcCanisterPageController {
    /// Canonical controller principal.
    pub principal_id: String,
    /// Raw optional Dashboard metadata associated with the controller.
    pub raw_metadata: Option<String>,
}

///
/// IcCanisterPageRow
///
/// One discovery row from a bounded Dashboard canister page.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcCanisterPageRow {
    /// Canonical canister principal.
    pub canister_id: String,
    /// Dashboard database row identifier.
    pub dashboard_id: u64,
    /// Raw optional Dashboard canister classification.
    pub canister_type: Option<String>,
    /// Raw Dashboard canister name.
    pub name: String,
    /// Canonical Subnet principal recorded by the Dashboard.
    pub subnet_id: String,
    /// Canonically ordered controller entries recorded by the Dashboard.
    pub controllers: Vec<IcCanisterPageController>,
    /// Raw Dashboard language label.
    pub language: String,
    /// Raw current module hash.
    pub module_hash: String,
    /// Raw Dashboard row update timestamp.
    pub dashboard_updated_at: String,
}

///
/// IcCanisterPageReport
///
/// One explicitly bounded page from the official Dashboard canister collection.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcCanisterPageReport {
    /// Shared Dashboard provenance, flattened in serialized report JSON.
    #[serde(flatten)]
    pub provenance: IcDashboardReportProvenance,
    /// Filters applied by the Dashboard.
    pub filters: IcCanisterFilters,
    /// Maximum rows requested from the API.
    pub requested_limit: u16,
    /// Number of rows returned in this report.
    pub returned_count: usize,
    /// Exclusive forward cursor supplied to this request.
    pub after: Option<String>,
    /// Exclusive backward cursor supplied to this request.
    pub before: Option<String>,
    /// Cursor for an explicit request for the preceding page.
    pub previous_cursor: Option<String>,
    /// Cursor for an explicit request for the following page.
    pub next_cursor: Option<String>,
    /// Canister discovery rows in Dashboard canister-id order.
    pub rows: Vec<IcCanisterPageRow>,
}

///
/// IcSourceRequest
///
/// Shared endpoint and collection provenance for IC Dashboard source calls and results.
///

#[cfg(feature = "host")]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcSourceRequest {
    /// Dashboard API base endpoint.
    pub endpoint: String,
    /// Collection timestamp in UTC.
    pub fetched_at: String,
    /// Collector identity recorded in report provenance.
    pub fetched_by: String,
}

#[cfg(feature = "host")]
impl IcSourceRequest {
    /// Construct source-call provenance.
    #[must_use]
    pub fn new(
        endpoint: impl Into<String>,
        fetched_at: impl Into<String>,
        fetched_by: impl Into<String>,
    ) -> Self {
        Self {
            endpoint: endpoint.into(),
            fetched_at: fetched_at.into(),
            fetched_by: fetched_by.into(),
        }
    }
}

///
/// IcCanisterSourceData
///
/// Raw canister metadata and provenance returned by an IC Dashboard source.
///

#[cfg(feature = "host")]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcCanisterSourceData {
    /// Source request and provenance preserved by the source.
    pub source: IcSourceRequest,
    /// Canister principal returned by the Dashboard.
    pub canister_id: String,
    /// Dashboard database row identifier.
    pub dashboard_id: u64,
    /// Raw optional Dashboard canister classification.
    pub canister_type: Option<String>,
    /// Raw Dashboard canister name.
    pub name: String,
    /// Subnet principal returned by the Dashboard.
    pub subnet_id: String,
    /// Controller principals returned by the Dashboard.
    pub controllers: Vec<String>,
    /// Raw Dashboard language label.
    pub language: String,
    /// Raw current module hash.
    pub module_hash: String,
    /// Raw Dashboard row update timestamp.
    pub dashboard_updated_at: String,
    /// Proposal-linked upgrades, or `None` when the Dashboard returned `null`.
    pub upgrades: Option<Vec<IcCanisterUpgrade>>,
}

///
/// IcCanisterCountSourceData
///
/// Raw filtered count and provenance returned by a Dashboard source.
///

#[cfg(feature = "host")]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcCanisterCountSourceData {
    /// Source request and provenance preserved by the source.
    pub source: IcSourceRequest,
    /// Filters applied by the source.
    pub filters: IcCanisterFilters,
    /// Number of matching Dashboard canister records.
    pub total: u64,
}

///
/// IcCanisterPageSourceData
///
/// Raw bounded canister page and provenance returned by a Dashboard source.
///

#[cfg(feature = "host")]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcCanisterPageSourceData {
    /// Source request and provenance preserved by the source.
    pub source: IcSourceRequest,
    /// Filters applied by the source.
    pub filters: IcCanisterFilters,
    /// Maximum rows requested from the source.
    pub requested_limit: u16,
    /// Exclusive forward cursor supplied to the source.
    pub after: Option<String>,
    /// Exclusive backward cursor supplied to the source.
    pub before: Option<String>,
    /// Cursor for an explicit request for the preceding page.
    pub previous_cursor: Option<String>,
    /// Cursor for an explicit request for the following page.
    pub next_cursor: Option<String>,
    /// Canister discovery rows returned by the source.
    pub rows: Vec<IcCanisterPageRow>,
}

///
/// IcMetricSourceData
///
/// Raw bounded metric series and provenance returned by a Dashboard source.
///

#[cfg(feature = "host")]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcMetricSourceData {
    /// Source request and provenance preserved by the source.
    pub source: IcSourceRequest,
    /// Metric query applied by the source.
    pub query: IcMetricQuery,
    /// Raw named time series returned by the source.
    pub series: Vec<IcMetricSeries>,
}

///
/// IcDailyStatsSourceData
///
/// Raw bounded daily network-activity rows and provenance returned by a source.
///

#[cfg(feature = "host")]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcDailyStatsSourceData {
    /// Source request and provenance preserved by the source.
    pub source: IcSourceRequest,
    /// Daily-statistics query applied by the source.
    pub query: IcDailyStatsQuery,
    /// Selected raw daily rows returned by the source.
    pub rows: Vec<IcDailyStatsRow>,
}

///
/// IcBoundaryNodeDataCentersSourceData
///
/// Raw boundary-node data-center rows and provenance returned by a Dashboard source.
///

#[cfg(feature = "host")]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcBoundaryNodeDataCentersSourceData {
    /// Source request and provenance preserved by the source.
    pub source: IcSourceRequest,
    /// Raw data-center rows returned by the source.
    pub rows: Vec<IcBoundaryNodeDataCenterRow>,
}

///
/// IcHostError
///
/// Typed error returned by IC Dashboard report builders and live sources.
///

#[cfg(feature = "host")]
#[derive(Debug, ThisError)]
pub enum IcHostError {
    /// The synchronous adapter could not create its local async runtime.
    #[error("failed to run IC Dashboard query: {0}")]
    Runtime(#[from] RuntimeError),

    /// A request supplied an invalid canister principal.
    #[error("invalid {field}: {reason}")]
    InvalidPrincipal {
        /// Principal field being validated.
        field: &'static str,
        /// Principal parser diagnostic.
        reason: String,
    },

    /// A request violates the bounded Dashboard query contract.
    #[error("invalid {field}: {reason}")]
    InvalidRequest {
        /// Request field being validated.
        field: &'static str,
        /// Deterministic validation diagnostic.
        reason: String,
    },

    /// The Dashboard API base endpoint is malformed or unsupported.
    #[error("invalid IC Dashboard endpoint {endpoint}: {reason}")]
    InvalidEndpoint {
        /// Rejected endpoint.
        endpoint: String,
        /// URL validation diagnostic.
        reason: String,
    },

    /// The HTTP client could not be constructed.
    #[error("failed to build IC Dashboard HTTP client: {reason}")]
    HttpClientBuild {
        /// HTTP client construction diagnostic.
        reason: String,
    },

    /// The live Dashboard request failed before a response was received.
    #[error("IC Dashboard request to {url} failed: {reason}")]
    HttpRequest {
        /// Fully resolved request URL.
        url: String,
        /// HTTP transport error.
        reason: String,
    },

    /// The Dashboard returned a non-success HTTP status.
    #[error("IC Dashboard request to {url} returned HTTP status {status}")]
    HttpStatus {
        /// Fully resolved request URL.
        url: String,
        /// Numeric HTTP status.
        status: u16,
    },

    /// The Dashboard response did not match the expected JSON shape.
    #[error("failed to decode IC Dashboard response from {url}: {reason}")]
    JsonDecode {
        /// Fully resolved request URL.
        url: String,
        /// JSON response decoding error.
        reason: String,
    },

    /// A source capability returned data that violates its public result contract.
    #[error("invalid IC Dashboard source data: {reason}")]
    InvalidSourceData {
        /// Deterministic invariant failure.
        reason: String,
    },
}