ic-query 0.45.12

Internet Computer query library for CloudEngine, 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
use crate::{
    cache_file::{CacheFileError, HostCacheError},
    ic_registry::RegistryFetchError,
    network::enforce_mainnet_network_with,
    runtime::RuntimeError,
    subnet_catalog::{CatalogAssurance, CatalogError},
};
use std::path::PathBuf;
use thiserror::Error as ThisError;

///
/// SubnetCatalogErrorCode
///
/// Stable machine-readable code for a Subnet Catalog host failure.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SubnetCatalogErrorCode {
    /// The requested network is unsupported.
    UnsupportedNetwork,
    /// The cache-only operation found no catalog.
    MissingCatalog,
    /// The retained catalog exceeded the fixed cache-read byte ceiling.
    CachedCatalogTooLarge,
    /// Caller supplied an incompatible cache read policy.
    InvalidReadPolicy,
    /// Caller supplied an invalid or unbounded source selection.
    InvalidSourceSelection,
    /// A source returned assurance evidence that did not match its request.
    SourceEvidenceMismatch,
    /// Loaded or selected evidence does not meet the caller's minimum assurance.
    InsufficientAssurance,
    /// One endpoint in an agreement collection failed.
    AgreementEndpoint,
    /// Independent endpoints did not return the same Registry snapshot.
    AgreementMismatch,
    /// Aggregating source call counts exceeded the report representation.
    RegistryQueryCallCountOverflow,
    /// The synchronous adapter could not run the async refresh core.
    RuntimeAdapter,
    /// A shared cache or lock operation failed.
    CacheOperation,
    /// Live Registry collection failed.
    RegistryRefresh,
    /// Raw catalog content failed deterministic validation.
    CatalogValidation,
}

impl SubnetCatalogErrorCode {
    /// Return the stable snake-case code.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::UnsupportedNetwork => "unsupported_network",
            Self::MissingCatalog => "missing_catalog",
            Self::CachedCatalogTooLarge => "cached_catalog_too_large",
            Self::InvalidReadPolicy => "invalid_read_policy",
            Self::InvalidSourceSelection => "invalid_source_selection",
            Self::SourceEvidenceMismatch => "source_evidence_mismatch",
            Self::InsufficientAssurance => "insufficient_assurance",
            Self::AgreementEndpoint => "agreement_endpoint",
            Self::AgreementMismatch => "agreement_mismatch",
            Self::RegistryQueryCallCountOverflow => "registry_query_call_count_overflow",
            Self::RuntimeAdapter => "runtime_adapter",
            Self::CacheOperation => "cache_operation",
            Self::RegistryRefresh => "registry_refresh",
            Self::CatalogValidation => "catalog_validation",
        }
    }
}

///
/// SubnetCatalogErrorCategory
///
/// Stable operational category for a Subnet Catalog host failure.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SubnetCatalogErrorCategory {
    /// Invalid caller input or policy.
    Input,
    /// Missing local evidence.
    Missing,
    /// Filesystem or refresh-lock failure.
    CacheIo,
    /// Managed cache path confinement or permission failure.
    Confinement,
    /// Network or remote Registry source failure.
    Network,
    /// Evidence identity or assurance failure.
    Authority,
    /// Deterministic raw catalog validation failure.
    Validation,
    /// Failure in the synchronous runtime adapter.
    Runtime,
}

impl SubnetCatalogErrorCategory {
    /// Return the stable snake-case category.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Input => "input",
            Self::Missing => "missing",
            Self::CacheIo => "cache_io",
            Self::Confinement => "confinement",
            Self::Network => "network",
            Self::Authority => "authority",
            Self::Validation => "validation",
            Self::Runtime => "runtime",
        }
    }
}

///
/// SubnetCatalogRetryability
///
/// Whether retrying without changing local inputs can reasonably succeed.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SubnetCatalogRetryability {
    /// A later retry may succeed without changing the request.
    Retryable,
    /// The caller must change policy, input, or local evidence first.
    NotRetryable,
    /// Available evidence does not support a truthful binary classification.
    Unknown(SubnetCatalogUnknownRetryReason),
}

impl SubnetCatalogRetryability {
    /// Return the stable snake-case classification.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Retryable => "retryable",
            Self::NotRetryable => "not_retryable",
            Self::Unknown(_) => "unknown",
        }
    }
}

///
/// SubnetCatalogUnknownRetryReason
///
/// Typed reason a Subnet Catalog host failure cannot be classified as retryable or not.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SubnetCatalogUnknownRetryReason {
    /// A filesystem operation may reflect either transient IO or persistent local state.
    CacheOperation,
    /// A Registry response failure may change, but no safe retry guarantee is available.
    RegistryResponse,
    /// A Registry transport failure does not expose enough typed detail to classify safely.
    RegistryTransport,
    /// Runtime availability cannot be inferred from the adapter failure alone.
    RuntimeAdapter,
}

impl SubnetCatalogUnknownRetryReason {
    /// Return the stable snake-case reason.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::CacheOperation => "cache_operation",
            Self::RegistryResponse => "registry_response",
            Self::RegistryTransport => "registry_transport",
            Self::RuntimeAdapter => "runtime_adapter",
        }
    }
}

///
/// SubnetCatalogRemediation
///
/// Structured remediation that a caller may render in its own vocabulary.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SubnetCatalogRemediation {
    /// Select the canonical mainnet `ic` network.
    UseMainnet,
    /// Explicitly refresh the Subnet Catalog.
    RefreshCatalog,
}

///
/// SubnetCatalogHostError
///
/// Errors returned by host-backed subnet catalog loading and refresh operations.
///

#[derive(Debug, ThisError)]
pub enum SubnetCatalogHostError {
    /// The request selected a network other than mainnet `ic`.
    #[error("unsupported Subnet Catalog network {network:?}; expected mainnet identity \"ic\"")]
    UnsupportedNetwork {
        /// Rejected network identity.
        network: String,
    },

    /// A cache-only read could not find the required catalog snapshot.
    #[error("subnet catalog cache is missing at {}", path.display())]
    MissingCatalog {
        /// Expected catalog snapshot path.
        path: PathBuf,
    },

    /// The retained catalog exceeded the fixed byte ceiling before decoding.
    #[error(
        "subnet catalog cache at {} exceeds its byte limit: observed {actual}, maximum {maximum}",
        path.display()
    )]
    CachedCatalogTooLarge {
        /// Rejected managed catalog path.
        path: PathBuf,
        /// Length observed in metadata or during the bounded read.
        actual: u64,
        /// Fixed cache-read byte ceiling.
        maximum: u64,
    },

    /// The requested cache operation received an incompatible read policy.
    #[error("invalid subnet catalog read policy: {reason}")]
    InvalidReadPolicy {
        /// Deterministic policy failure.
        reason: String,
    },

    /// Caller supplied an invalid source selection.
    #[error("invalid subnet catalog source selection: {reason}")]
    InvalidSourceSelection {
        /// Deterministic selection failure.
        reason: String,
    },

    /// A custom source returned assurance or endpoints other than the request.
    #[error(
        "subnet catalog source returned assurance {} and endpoints {actual_endpoints:?}; requested single endpoint was {requested:?}",
        actual_assurance.as_str()
    )]
    SourceEvidenceMismatch {
        /// Requested source endpoint.
        requested: String,
        /// Assurance claimed by the returned evidence.
        actual_assurance: CatalogAssurance,
        /// Complete endpoint list recorded by returned evidence.
        actual_endpoints: Vec<String>,
    },

    /// Valid evidence or a selected source is weaker than the caller requires.
    #[error(
        "subnet catalog assurance {} does not meet required minimum {}",
        actual.as_str(),
        required.as_str()
    )]
    InsufficientAssurance {
        /// Minimum assurance required by the caller.
        required: CatalogAssurance,
        /// Assurance supplied by the cache or selected refresh source.
        actual: CatalogAssurance,
    },

    /// One endpoint failed during a bounded agreement collection.
    #[error("subnet catalog agreement endpoint {endpoint:?} failed: {source}")]
    AgreementEndpoint {
        /// Exact endpoint whose collection failed.
        endpoint: String,
        /// Typed source failure.
        source: Box<Self>,
    },

    /// One endpoint disagreed with the first canonical Registry snapshot.
    #[error(
        "subnet catalog endpoint agreement failed: {endpoint:?} returned registry_version={registry_version} digest={agreement_digest}, but {reference_endpoint:?} returned registry_version={reference_registry_version} digest={reference_agreement_digest}"
    )]
    AgreementMismatch {
        /// First canonical endpoint.
        reference_endpoint: String,
        /// Registry version returned by the first endpoint.
        reference_registry_version: u64,
        /// Canonical Registry payload digest returned by the first endpoint.
        reference_agreement_digest: String,
        /// Differing endpoint.
        endpoint: String,
        /// Registry version returned by the differing endpoint.
        registry_version: u64,
        /// Canonical Registry payload digest returned by the differing endpoint.
        agreement_digest: String,
    },

    /// Summed Registry query call count cannot be represented as `u64`.
    #[error("subnet catalog Registry query call count overflowed u64")]
    RegistryQueryCallCountOverflow,

    /// Synchronous adapter failed to run the caller-owned async implementation.
    #[error(transparent)]
    RuntimeAdapter(#[from] RuntimeError),

    /// Confined cache IO or refresh locking failed.
    #[error(transparent)]
    Cache(#[from] HostCacheError),

    /// Live Registry collection failed before catalog publication.
    #[error("live NNS registry refresh failed: {0}")]
    RegistryRefresh(#[from] RegistryFetchError),

    /// Collected or retained catalog evidence failed validation or resolution.
    #[error(transparent)]
    Catalog(#[from] CatalogError),
}

impl SubnetCatalogHostError {
    /// Return the stable machine-readable error code.
    #[must_use]
    pub const fn code(&self) -> SubnetCatalogErrorCode {
        match self {
            Self::UnsupportedNetwork { .. } => SubnetCatalogErrorCode::UnsupportedNetwork,
            Self::MissingCatalog { .. } => SubnetCatalogErrorCode::MissingCatalog,
            Self::CachedCatalogTooLarge { .. } => SubnetCatalogErrorCode::CachedCatalogTooLarge,
            Self::InvalidReadPolicy { .. } => SubnetCatalogErrorCode::InvalidReadPolicy,
            Self::InvalidSourceSelection { .. } => SubnetCatalogErrorCode::InvalidSourceSelection,
            Self::SourceEvidenceMismatch { .. } => SubnetCatalogErrorCode::SourceEvidenceMismatch,
            Self::InsufficientAssurance { .. } => SubnetCatalogErrorCode::InsufficientAssurance,
            Self::AgreementEndpoint { .. } => SubnetCatalogErrorCode::AgreementEndpoint,
            Self::AgreementMismatch { .. } => SubnetCatalogErrorCode::AgreementMismatch,
            Self::RegistryQueryCallCountOverflow => {
                SubnetCatalogErrorCode::RegistryQueryCallCountOverflow
            }
            Self::RuntimeAdapter(_) => SubnetCatalogErrorCode::RuntimeAdapter,
            Self::Cache(_) => SubnetCatalogErrorCode::CacheOperation,
            Self::RegistryRefresh(_) => SubnetCatalogErrorCode::RegistryRefresh,
            Self::Catalog(_) => SubnetCatalogErrorCode::CatalogValidation,
        }
    }

    /// Return the stable operational error category.
    #[must_use]
    pub fn category(&self) -> SubnetCatalogErrorCategory {
        match self {
            Self::UnsupportedNetwork { .. }
            | Self::InvalidReadPolicy { .. }
            | Self::InvalidSourceSelection { .. } => SubnetCatalogErrorCategory::Input,
            Self::MissingCatalog { .. } => SubnetCatalogErrorCategory::Missing,
            Self::Cache(HostCacheError::Operation {
                source:
                    CacheFileError::UnsupportedConfinementPlatform { .. }
                    | CacheFileError::Confinement { .. }
                    | CacheFileError::UnsafeManagedPermissions { .. },
                ..
            })
            | Self::RegistryRefresh(RegistryFetchError::HistoryCache(
                HostCacheError::Operation {
                    source:
                        CacheFileError::UnsupportedConfinementPlatform { .. }
                        | CacheFileError::Confinement { .. }
                        | CacheFileError::UnsafeManagedPermissions { .. },
                    ..
                },
            )) => SubnetCatalogErrorCategory::Confinement,
            Self::Cache(_) | Self::RegistryRefresh(RegistryFetchError::HistoryCache(_)) => {
                SubnetCatalogErrorCategory::CacheIo
            }
            Self::RegistryRefresh(_) => SubnetCatalogErrorCategory::Network,
            Self::AgreementEndpoint { source, .. } => source.category(),
            Self::SourceEvidenceMismatch { .. }
            | Self::InsufficientAssurance { .. }
            | Self::AgreementMismatch { .. }
            | Self::Catalog(
                CatalogError::NetworkMismatch { .. }
                | CatalogError::RegistryCanisterMismatch { .. }
                | CatalogError::UnsupportedAssurance { .. }
                | CatalogError::ClassificationPolicyVersionMismatch { .. }
                | CatalogError::ClassificationPolicyDigestMismatch { .. }
                | CatalogError::ResolverPolicyMismatch { .. }
                | CatalogError::CatalogDigestMismatch { .. },
            ) => SubnetCatalogErrorCategory::Authority,
            Self::RuntimeAdapter(_) => SubnetCatalogErrorCategory::Runtime,
            Self::CachedCatalogTooLarge { .. }
            | Self::RegistryQueryCallCountOverflow
            | Self::Catalog(_) => SubnetCatalogErrorCategory::Validation,
        }
    }

    /// Return whether an unchanged retry may reasonably succeed.
    #[must_use]
    pub fn retryability(&self) -> SubnetCatalogRetryability {
        match self {
            Self::AgreementEndpoint { source, .. } => source.retryability(),
            Self::RegistryRefresh(source) => registry_retryability(source),
            Self::AgreementMismatch { .. } => SubnetCatalogRetryability::Retryable,
            Self::RuntimeAdapter(_) => {
                SubnetCatalogRetryability::Unknown(SubnetCatalogUnknownRetryReason::RuntimeAdapter)
            }
            Self::Cache(_) => {
                SubnetCatalogRetryability::Unknown(SubnetCatalogUnknownRetryReason::CacheOperation)
            }
            _ => SubnetCatalogRetryability::NotRetryable,
        }
    }

    /// Return structured remediation when one action is unambiguous.
    #[must_use]
    pub const fn remediation(&self) -> Option<SubnetCatalogRemediation> {
        match self {
            Self::UnsupportedNetwork { .. } => Some(SubnetCatalogRemediation::UseMainnet),
            Self::MissingCatalog { .. } => Some(SubnetCatalogRemediation::RefreshCatalog),
            _ => None,
        }
    }
}

const fn registry_retryability(error: &RegistryFetchError) -> SubnetCatalogRetryability {
    match error {
        RegistryFetchError::HistoryCache(_) => {
            SubnetCatalogRetryability::Unknown(SubnetCatalogUnknownRetryReason::CacheOperation)
        }
        RegistryFetchError::AgentCall { .. } => {
            SubnetCatalogRetryability::Unknown(SubnetCatalogUnknownRetryReason::RegistryTransport)
        }
        RegistryFetchError::EmptyRegistryChunkList
        | RegistryFetchError::InvalidRegistryChunkDigest { .. }
        | RegistryFetchError::ProtobufDecode { .. }
        | RegistryFetchError::RegistryValue { .. }
        | RegistryFetchError::MissingValue { .. }
        | RegistryFetchError::InvalidRegistryValueVersion { .. }
        | RegistryFetchError::RegistryChanges { .. }
        | RegistryFetchError::IncompleteRegistryChanges { .. }
        | RegistryFetchError::InvalidRegistryKeyFamily { .. }
        | RegistryFetchError::CandidDecode { .. }
        | RegistryFetchError::RegistryChunkRejected { .. }
        | RegistryFetchError::MissingChunkContent { .. }
        | RegistryFetchError::ChunkHashMismatch { .. }
        | RegistryFetchError::MissingField { .. }
        | RegistryFetchError::CountOverflow { .. }
        | RegistryFetchError::InvalidPrincipal { .. }
        | RegistryFetchError::DuplicateNodeAssignment { .. }
        | RegistryFetchError::MissingNodeRecord { .. }
        | RegistryFetchError::MissingNodeOperatorPrincipal { .. }
        | RegistryFetchError::MissingNodeOperatorRecord { .. }
        | RegistryFetchError::MissingNodeProviderPrincipal { .. }
        | RegistryFetchError::InvalidDataCenterRecordId { .. }
        | RegistryFetchError::EmptySubnetList
        | RegistryFetchError::DuplicateSubnetPrincipal { .. }
        | RegistryFetchError::EmptyRoutingTable
        | RegistryFetchError::Catalog(_)
        | RegistryFetchError::CertificateAuthentication { .. }
        | RegistryFetchError::InvalidCertifiedRegistry { .. } => {
            SubnetCatalogRetryability::Unknown(SubnetCatalogUnknownRetryReason::RegistryResponse)
        }
        RegistryFetchError::Runtime(_) => {
            SubnetCatalogRetryability::Unknown(SubnetCatalogUnknownRetryReason::RuntimeAdapter)
        }
        RegistryFetchError::AgentBuild { .. }
        | RegistryFetchError::RegistryChunkLimit { .. }
        | RegistryFetchError::RegistryKeyFamilyLimit { .. }
        | RegistryFetchError::ProtobufEncode { .. }
        | RegistryFetchError::CandidEncode { .. } => SubnetCatalogRetryability::NotRetryable,
    }
}

pub(super) fn enforce_mainnet_network(network: &str) -> Result<(), SubnetCatalogHostError> {
    enforce_mainnet_network_with(network, |network| {
        SubnetCatalogHostError::UnsupportedNetwork { network }
    })
}

pub(super) fn subnet_cache_error(err: CacheFileError) -> SubnetCatalogHostError {
    HostCacheError::operation("subnet catalog", err).into()
}