ic-query 0.28.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
//! Module: ic::node_status::model
//!
//! Responsibility: public observed node-status requests, evidence, reports, and errors.
//! Does not own: source calls, cache IO, projection, or rendering.
//! Boundary: preserves raw Dashboard status data and explicit off-chain/cache provenance.

use crate::ic::IcDashboardReportProvenance;
use serde::{Deserialize as SerdeDeserialize, Serialize};
use std::fmt;
#[cfg(feature = "host")]
use std::path::PathBuf;
use thiserror::Error as ThisError;

///
/// IcNodeStatusScope
///
/// Dashboard collection scope retained by an observed node-status snapshot.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq, SerdeDeserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum IcNodeStatusScope {
    /// Dashboard's default public-mainnet node set, excluding cloud-engine Type4 nodes.
    DashboardMainnetDefault,
}

impl IcNodeStatusScope {
    /// Return the stable serialized scope label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::DashboardMainnetDefault => super::IC_NODE_STATUS_SCOPE,
        }
    }
}

///
/// IcNodeOperationalStatus
///
/// Known Dashboard node-status classification used for filtering and counts.
///

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum IcNodeOperationalStatus {
    /// The Dashboard reports the node as up.
    Up,
    /// The Dashboard reports the node as down.
    Down,
    /// The Dashboard reports the node as administratively disabled.
    Disabled,
    /// The Dashboard reports degraded operation.
    Degraded,
    /// The raw Dashboard value is not recognized by this release.
    Unknown,
}

impl IcNodeOperationalStatus {
    /// Classify raw Dashboard status text without discarding unknown future values.
    #[must_use]
    pub fn from_raw(raw: &str) -> Self {
        match raw {
            "UP" => Self::Up,
            "DOWN" => Self::Down,
            "DISABLED" => Self::Disabled,
            "DEGRADED" => Self::Degraded,
            _ => Self::Unknown,
        }
    }

    /// Return the stable lowercase display label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Up => "up",
            Self::Down => "down",
            Self::Disabled => "disabled",
            Self::Degraded => "degraded",
            Self::Unknown => "unknown",
        }
    }
}

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

///
/// IcNodeStatusCounts
///
/// Exact status totals derived from raw observed node rows.
///

#[derive(Clone, Debug, Default, Eq, PartialEq, SerdeDeserialize, Serialize)]
pub struct IcNodeStatusCounts {
    /// Total observed rows in the group.
    pub total: usize,
    /// Rows classified as `UP`.
    pub up: usize,
    /// Rows classified as `DOWN`.
    pub down: usize,
    /// Rows classified as `DISABLED`.
    pub disabled: usize,
    /// Rows classified as `DEGRADED`.
    pub degraded: usize,
    /// Rows whose raw status is not recognized.
    pub unknown: usize,
}

impl IcNodeStatusCounts {
    /// Return every row not classified as raw Dashboard `UP`.
    #[must_use]
    pub const fn non_up(&self) -> usize {
        self.total.saturating_sub(self.up)
    }
}

///
/// IcNodeAssignmentStatusCounts
///
/// Operational-status totals partitioned by mutually exclusive assignment class.
///

#[derive(Clone, Debug, Default, Eq, PartialEq, SerdeDeserialize, Serialize)]
pub struct IcNodeAssignmentStatusCounts {
    /// Status totals for nodes with an observed assigned Subnet.
    pub assigned: IcNodeStatusCounts,
    /// Status totals for rows whose raw node type is `UNASSIGNED`.
    pub unassigned: IcNodeStatusCounts,
    /// Status totals for rows whose raw node type is `API_BOUNDARY`.
    pub api_boundary: IcNodeStatusCounts,
    /// Status totals for rows without a known assignment class.
    pub unknown: IcNodeStatusCounts,
}

///
/// IcNodeStatusGroupCounts
///
/// Overall and assignment-partitioned status totals for one aggregate group.
///

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
pub struct IcNodeStatusGroupCounts {
    /// Raw operational-status totals for the group.
    pub statuses: IcNodeStatusCounts,
    /// Raw operational-status totals partitioned by assignment class.
    pub assignment_statuses: IcNodeAssignmentStatusCounts,
}

///
/// IcNodeStatusRow
///
/// One raw node observation retained from the official Dashboard node resource.
///

#[derive(Clone, Debug, Eq, PartialEq, SerdeDeserialize, Serialize)]
pub struct IcNodeStatusRow {
    /// Canonical node principal.
    pub node_id: String,
    /// Canonical node-operator principal.
    pub node_operator_id: String,
    /// Canonical node-provider principal.
    pub node_provider_id: String,
    /// Off-chain Dashboard node-provider name.
    pub node_provider_name: String,
    /// Raw Dashboard node type.
    pub node_type: String,
    /// Raw Registry reward type reported by the Dashboard.
    pub node_reward_type: String,
    /// Raw Dashboard operational status.
    pub status: String,
    /// Raw Dashboard alert name when present.
    pub alert_name: Option<String>,
    /// Assigned Subnet principal when present.
    pub subnet_id: Option<String>,
    /// Cloud-engine Subnet principal when present in a future compatible scope.
    pub cloud_engine_subnet_id: Option<String>,
    /// Dashboard data-center identifier.
    pub data_center_id: String,
    /// Dashboard data-center name.
    pub data_center_name: String,
    /// Dashboard infrastructure owner label.
    pub owner: String,
    /// Raw Dashboard geographic region label.
    pub region: String,
    /// Observed GuestOS version when reported.
    pub guestos_version: Option<String>,
    /// Observed GuestOS trusted-execution status when reported.
    pub guestos_tee_active: Option<bool>,
    /// Observed node IP address when reported.
    pub ip_address: Option<String>,
    /// Observed IPv4-connectivity state when reported.
    pub ipv4_connectivity_status: Option<bool>,
    /// Dashboard hardware-generation label when reported.
    pub node_hardware_generation: Option<String>,
}

impl IcNodeStatusRow {
    /// Return the known classification of this row's raw status.
    #[must_use]
    pub fn operational_status(&self) -> IcNodeOperationalStatus {
        IcNodeOperationalStatus::from_raw(&self.status)
    }

    /// Return whether the raw row is anything other than known `UP`.
    #[must_use]
    pub fn is_non_up(&self) -> bool {
        self.operational_status() != IcNodeOperationalStatus::Up
    }
}

///
/// IcNodeStatusCacheEvidence
///
/// Caller-relative local cache evidence attached to a projected status report.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcNodeStatusCacheEvidence {
    /// Canonical local cache path used by the report.
    pub cache_path: String,
    /// Whether the cache is within the default age policy for this caller's time.
    pub cache_fresh: bool,
    /// Cache age at report construction.
    pub age_seconds: u64,
    /// Age threshold used to classify freshness.
    pub stale_after_seconds: u64,
}

///
/// IcNodeStatusObservation
///
/// Shared source, scope, and optional cache evidence for status reports.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcNodeStatusObservation {
    #[serde(flatten)]
    /// Official Dashboard source provenance.
    pub source: IcDashboardReportProvenance,
    /// Explicit node collection scope.
    pub scope: IcNodeStatusScope,
    /// Whether cloud-engine nodes were included in the source collection.
    pub cloud_engine_nodes_included: bool,
    /// Local cache evidence, absent for a pure live snapshot.
    pub cache: Option<IcNodeStatusCacheEvidence>,
}

///
/// IcNodeStatusSnapshot
///
/// Complete canonical observed node snapshot used by every status projection.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcNodeStatusSnapshot {
    #[serde(flatten)]
    /// Shared source and scope evidence.
    pub observation: IcNodeStatusObservation,
    /// Exact number of raw node rows.
    pub node_count: usize,
    /// Snapshot-wide overall and assignment-partitioned totals.
    pub counts: IcNodeStatusGroupCounts,
    /// Canonically ordered raw node rows.
    pub nodes: Vec<IcNodeStatusRow>,
}

///
/// IcNodeStatusSnapshotRequest
///
/// Request for one live finite Dashboard node-status snapshot.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcNodeStatusSnapshotRequest {
    /// Dashboard API v3 base endpoint.
    pub source_endpoint: String,
    /// Caller-supplied collection timestamp as Unix seconds.
    pub now_unix_secs: u64,
}

impl IcNodeStatusSnapshotRequest {
    /// Construct one live node-status snapshot 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,
        }
    }
}

///
/// IcNodeStatusSourceData
///
/// Untrusted raw node rows and provenance returned by a Dashboard source capability.
///

#[cfg(feature = "host")]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcNodeStatusSourceData {
    /// Source-call provenance echoed by the source.
    pub source: crate::ic::IcSourceRequest,
    /// Explicit Dashboard collection scope.
    pub scope: IcNodeStatusScope,
    /// Whether the source claims cloud-engine node inclusion.
    pub cloud_engine_nodes_included: bool,
    /// Raw observed node rows.
    pub nodes: Vec<IcNodeStatusRow>,
}

///
/// IcNodeStatusView
///
/// Target and attention selection shared by node, Subnet, and provider views.
///

#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct IcNodeStatusView {
    /// Optional exact identifier or unique principal prefix.
    pub target: Option<String>,
    /// Whether fully-up rows or groups are included without a target.
    pub include_all: bool,
}

impl IcNodeStatusView {
    /// Construct the default attention-only view.
    #[must_use]
    pub const fn attention() -> Self {
        Self {
            target: None,
            include_all: false,
        }
    }

    /// Select one exact identifier or unique principal prefix.
    #[must_use]
    pub fn with_target(mut self, target: impl Into<String>) -> Self {
        self.target = Some(target.into());
        self
    }

    /// Include fully-up rows as well as attention rows.
    #[must_use]
    pub const fn with_all(mut self, include_all: bool) -> Self {
        self.include_all = include_all;
        self
    }
}

///
/// IcNodeStatusReport
///
/// Node-level view over one complete observed status snapshot.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcNodeStatusReport {
    #[serde(flatten)]
    /// Shared source, scope, and cache evidence.
    pub observation: IcNodeStatusObservation,
    /// Total rows in the complete source snapshot.
    pub snapshot_node_count: usize,
    /// Snapshot-wide overall and assignment-partitioned totals.
    pub counts: IcNodeStatusGroupCounts,
    /// Whether the view includes fully-up rows.
    pub include_all: bool,
    /// Target text supplied by the caller.
    pub requested_target: Option<String>,
    /// Canonical target resolved by exact or unique-prefix matching.
    pub resolved_target: Option<String>,
    /// Stable label describing how the target resolved.
    pub resolved_from: Option<String>,
    /// Number of returned node rows.
    pub returned_node_count: usize,
    /// Selected canonical node rows.
    pub nodes: Vec<IcNodeStatusRow>,
}

///
/// IcSubnetStatusRow
///
/// Observed operational counts and conservative threshold evidence for one Subnet.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcSubnetStatusRow {
    /// Canonical Subnet principal.
    pub subnet_id: String,
    /// Operational-status totals for observed assigned nodes.
    pub statuses: IcNodeStatusCounts,
    /// Byzantine fault count `floor((n - 1) / 3)` for the observed membership size.
    pub fault_tolerance_node_count: usize,
    /// Additional down nodes required for the down count to exceed the derived threshold.
    pub additional_down_nodes_to_exceed_fault_tolerance: usize,
    /// Additional non-up nodes required for the conservative count to exceed the threshold.
    pub additional_non_up_nodes_to_exceed_fault_tolerance: usize,
    /// Whether the observed down count already exceeds the derived threshold.
    pub down_fault_tolerance_exceeded: bool,
    /// Whether the observed conservative non-up count already exceeds the threshold.
    pub conservative_non_up_fault_tolerance_exceeded: bool,
    /// Raw non-up node evidence in canonical node order.
    pub non_up_nodes: Vec<IcNodeStatusRow>,
}

///
/// IcSubnetStatusReport
///
/// Subnet-level operational view over one complete observed node snapshot.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcSubnetStatusReport {
    #[serde(flatten)]
    /// Shared source, scope, and cache evidence.
    pub observation: IcNodeStatusObservation,
    /// Total rows in the complete source snapshot.
    pub snapshot_node_count: usize,
    /// Snapshot rows with an assigned Subnet.
    pub assigned_node_count: usize,
    /// Number of observed Subnets before view filtering.
    pub subnet_count: usize,
    /// Number of observed Subnets containing a non-up node.
    pub attention_subnet_count: usize,
    /// Whether fully-up Subnets are included without a target.
    pub include_all: bool,
    /// Target text supplied by the caller.
    pub requested_target: Option<String>,
    /// Canonical Subnet target resolved by exact or unique-prefix matching.
    pub resolved_target: Option<String>,
    /// Stable label describing how the target resolved.
    pub resolved_from: Option<String>,
    /// Number of returned Subnet rows.
    pub returned_subnet_count: usize,
    /// Canonically ordered selected Subnet rows.
    pub subnets: Vec<IcSubnetStatusRow>,
}

///
/// IcNodeProviderStatusRow
///
/// Assignment and raw operational counts for one observed node provider.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcNodeProviderStatusRow {
    /// Canonical node-provider principal.
    pub node_provider_id: String,
    /// Off-chain Dashboard provider name.
    pub node_provider_name: String,
    /// Operational-status and assignment totals for the provider.
    pub counts: IcNodeStatusGroupCounts,
    /// Raw non-up node evidence in canonical node order.
    pub non_up_nodes: Vec<IcNodeStatusRow>,
}

///
/// IcNodeProviderStatusReport
///
/// Node-provider operational view over one complete observed node snapshot.
///

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcNodeProviderStatusReport {
    #[serde(flatten)]
    /// Shared source, scope, and cache evidence.
    pub observation: IcNodeStatusObservation,
    /// Total rows in the complete source snapshot.
    pub snapshot_node_count: usize,
    /// Number of observed provider principals before view filtering.
    pub provider_count: usize,
    /// Number of provider groups containing a non-up node.
    pub attention_provider_count: usize,
    /// Whether fully-up providers are included without a target.
    pub include_all: bool,
    /// Target text supplied by the caller.
    pub requested_target: Option<String>,
    /// Canonical provider target resolved by exact or unique-prefix matching.
    pub resolved_target: Option<String>,
    /// Stable label describing how the target resolved.
    pub resolved_from: Option<String>,
    /// Number of returned provider rows.
    pub returned_provider_count: usize,
    /// Canonically ordered selected provider rows.
    pub providers: Vec<IcNodeProviderStatusRow>,
}

///
/// IcNodeStatusProjectionError
///
/// Failure to resolve or project a requested observed status view.
///

#[derive(Clone, Debug, Eq, PartialEq, ThisError)]
pub enum IcNodeStatusProjectionError {
    /// Snapshot-level counts or canonical ordering do not match raw rows.
    #[error("invalid observed node-status snapshot: {reason}")]
    InvalidSnapshot {
        /// Deterministic validation failure.
        reason: String,
    },
    /// The supplied target is empty after trimming.
    #[error("{kind} target must not be empty")]
    EmptyTarget {
        /// Projection kind being selected.
        kind: &'static str,
    },
    /// No observed identifier matches the supplied target.
    #[error("{kind} target {target:?} did not match the observed snapshot")]
    UnknownTarget {
        /// Projection kind being selected.
        kind: &'static str,
        /// Unmatched target text.
        target: String,
    },
    /// More than one observed identifier matches the supplied prefix.
    #[error("{kind} prefix {prefix:?} is ambiguous; matches: {matches:?}")]
    AmbiguousTarget {
        /// Projection kind being selected.
        kind: &'static str,
        /// Ambiguous principal prefix.
        prefix: String,
        /// Canonically ordered matching principals.
        matches: Vec<String>,
    },
}

///
/// IcNodeStatusCacheRequest
///
/// Stable identity of one network-level observed node-status cache.
///

#[cfg(feature = "host")]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcNodeStatusCacheRequest {
    /// Root directory containing all `ic-query` caches.
    pub cache_root: PathBuf,
    /// Requested network name.
    pub network: String,
}

#[cfg(feature = "host")]
impl IcNodeStatusCacheRequest {
    /// Construct one observed node-status cache identity.
    #[must_use]
    pub fn new(cache_root: impl Into<PathBuf>, network: impl Into<String>) -> Self {
        Self {
            cache_root: cache_root.into(),
            network: network.into(),
        }
    }
}

///
/// IcNodeStatusRefreshRequest
///
/// Settings for one forced observed node-status snapshot refresh.
///

#[cfg(feature = "host")]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcNodeStatusRefreshRequest {
    /// Stable cache identity.
    pub cache: IcNodeStatusCacheRequest,
    /// Explicit Dashboard API base endpoint.
    pub source_endpoint: String,
    /// Caller-supplied observation time as Unix seconds.
    pub now_unix_secs: u64,
    /// Age after which an abandoned refresh lock can be reclaimed.
    pub lock_stale_after_seconds: u64,
}

#[cfg(feature = "host")]
impl IcNodeStatusRefreshRequest {
    /// Construct one forced node-status snapshot refresh request.
    #[must_use]
    pub fn new(
        cache_root: impl Into<PathBuf>,
        network: impl Into<String>,
        source_endpoint: impl Into<String>,
        now_unix_secs: u64,
        lock_stale_after_seconds: u64,
    ) -> Self {
        Self {
            cache: IcNodeStatusCacheRequest::new(cache_root, network),
            source_endpoint: source_endpoint.into(),
            now_unix_secs,
            lock_stale_after_seconds,
        }
    }
}

///
/// IcNodeStatusReadRequest
///
/// Cache-backed status-view request shared by node, Subnet, and provider reports.
///

#[cfg(feature = "host")]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcNodeStatusReadRequest {
    /// Live and cache settings used when refresh is required.
    pub refresh: IcNodeStatusRefreshRequest,
    /// Projection target and attention selection.
    pub view: IcNodeStatusView,
    /// Whether to force a live replacement before reading.
    pub force_refresh: bool,
}

#[cfg(feature = "host")]
impl IcNodeStatusReadRequest {
    /// Construct one stale-refresh status-view request.
    #[must_use]
    pub fn new(
        cache_root: impl Into<PathBuf>,
        network: impl Into<String>,
        source_endpoint: impl Into<String>,
        now_unix_secs: u64,
    ) -> Self {
        Self {
            refresh: IcNodeStatusRefreshRequest::new(
                cache_root,
                network,
                source_endpoint,
                now_unix_secs,
                super::DEFAULT_IC_NODE_STATUS_REFRESH_LOCK_STALE_SECONDS,
            ),
            view: IcNodeStatusView::attention(),
            force_refresh: false,
        }
    }

    /// Apply one target and attention selection.
    #[must_use]
    pub fn with_view(mut self, view: IcNodeStatusView) -> Self {
        self.view = view;
        self
    }

    /// Select a forced refresh before projecting the report.
    #[must_use]
    pub const fn with_force_refresh(mut self, force_refresh: bool) -> Self {
        self.force_refresh = force_refresh;
        self
    }
}

///
/// IcNodeStatusRefreshReport
///
/// Result of atomically replacing the complete observed node-status cache.
///

#[cfg(feature = "host")]
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct IcNodeStatusRefreshReport {
    /// Cache/report schema version.
    pub schema_version: u32,
    /// Network identity attached to the replacement.
    pub network: String,
    /// Explicit Dashboard endpoint queried.
    pub source_endpoint: String,
    /// Canonical UTC collection timestamp.
    pub fetched_at: String,
    /// Collector identity.
    pub fetched_by: String,
    /// Published cache path.
    pub cache_path: String,
    /// Sibling refresh-lock path.
    pub refresh_lock_path: String,
    /// Whether an existing complete snapshot was replaced.
    pub replaced_existing_cache: bool,
    /// Number of published node rows.
    pub node_count: usize,
    /// Published overall and assignment-partitioned status totals.
    pub counts: IcNodeStatusGroupCounts,
}

///
/// IcNodeStatusHostError
///
/// Host source, cache, and projection failures for observed node-status reports.
///

#[cfg(feature = "host")]
#[derive(Debug, ThisError)]
pub enum IcNodeStatusHostError {
    /// The observed Dashboard source supports only public mainnet identity.
    #[error("observed IC node status supports only the mainnet `ic` network, not {network:?}")]
    UnsupportedNetwork {
        /// Unsupported requested network.
        network: String,
    },
    /// Live-source or source-validation failure.
    #[error(transparent)]
    Source(#[from] crate::ic::IcHostError),
    /// Pure projection failure.
    #[error(transparent)]
    Projection(#[from] IcNodeStatusProjectionError),
    /// Strict cache load found no complete snapshot.
    #[error("observed node-status cache is missing at {}", path.display())]
    MissingCache {
        /// Expected cache path.
        path: PathBuf,
    },
    /// Existing cache content could not be read.
    #[error("failed to read observed node-status cache at {}: {source}", path.display())]
    ReadCache {
        /// Cache path that failed.
        path: PathBuf,
        /// Underlying filesystem failure.
        source: std::io::Error,
    },
    /// Existing cache content was not valid JSON for the schema.
    #[error("failed to parse observed node-status cache at {}: {source}", path.display())]
    ParseCache {
        /// Cache path that failed.
        path: PathBuf,
        /// Underlying JSON failure.
        source: serde_json::Error,
    },
    /// Existing cache uses an unsupported schema version.
    #[error("observed node-status cache schema {version} is unsupported; expected {expected}")]
    UnsupportedCacheSchemaVersion {
        /// Observed schema version.
        version: u32,
        /// Required current schema version.
        expected: u32,
    },
    /// Existing cache belongs to another network.
    #[error("observed node-status cache network is {actual:?}, expected {requested:?}")]
    CacheNetworkMismatch {
        /// Requested network.
        requested: String,
        /// Network stored by the cache.
        actual: String,
    },
    /// Existing cache snapshot-key identity does not match its path.
    #[error(
        "observed node-status cache identity mismatch at {}: {field} is {actual:?}, expected {expected:?}",
        path.display()
    )]
    CacheIdentityMismatch {
        /// Cache path that failed validation.
        path: PathBuf,
        /// Identity field that differs.
        field: &'static str,
        /// Required identity value.
        expected: String,
        /// Stored identity value.
        actual: String,
    },
    /// Existing cache is structurally readable but semantically invalid.
    #[error("invalid observed node-status cache at {}: {reason}", path.display())]
    InvalidCache {
        /// Cache path that failed validation.
        path: PathBuf,
        /// Deterministic validation failure.
        reason: String,
    },
    /// A complete replacement could not be serialized.
    #[error("failed to serialize observed node-status cache at {}: {source}", path.display())]
    SerializeCache {
        /// Target cache path.
        path: PathBuf,
        /// Underlying JSON serialization failure.
        source: serde_json::Error,
    },
    /// Shared atomic cache or refresh-lock operation failed.
    #[error(transparent)]
    Cache(#[from] crate::cache_file::HostCacheError),
}