Skip to main content

ic_bn_lib/
lib.rs

1// Needed for certain macros
2#![recursion_limit = "256"]
3#![warn(clippy::nursery)]
4#![warn(tail_expr_drop_order)]
5#![allow(clippy::cognitive_complexity)]
6#![allow(clippy::field_reassign_with_default)]
7#![allow(clippy::collapsible_if)]
8// False positive on `#[derive(new)]` (derive-new) since clippy 1.99
9#![allow(clippy::redundant_field_names)]
10
11#[cfg(feature = "custom-domains")]
12pub mod custom_domains;
13pub mod dns;
14pub mod geoip;
15pub mod health;
16pub mod http;
17pub mod ic;
18#[cfg(feature = "lb")]
19pub mod lb;
20pub mod network;
21#[cfg(feature = "pubsub")]
22pub mod pubsub;
23#[cfg(all(target_os = "linux", feature = "sev-snp"))]
24pub mod sev_snp;
25#[cfg(feature = "smtp")]
26pub mod smtp;
27pub mod tasks;
28pub mod tests;
29pub mod tls;
30#[cfg(feature = "vector")]
31pub mod vector;
32
33use std::{fmt::Display, fs::File, net::IpAddr, path::Path, time::Duration};
34
35use anyhow::{Context, anyhow};
36use bytes::Bytes;
37use candid::Principal;
38use futures::StreamExt;
39use serde::{Deserialize, Serialize};
40use strum::{Display, EnumString, IntoStaticStr};
41use tokio::io::AsyncWriteExt;
42
43pub use hickory_proto;
44pub use hickory_resolver;
45pub use hyper;
46pub use hyper_util;
47pub use ic_agent;
48pub use ic_transport_types;
49pub use ipnet;
50#[cfg(feature = "smtp")]
51pub use mail_auth;
52pub use prometheus;
53#[cfg(feature = "acme")]
54pub use rcgen;
55pub use reqwest;
56pub use rustls;
57#[cfg(feature = "acme-alpn")]
58pub use rustls_acme;
59pub use show_option;
60pub use uuid;
61
62/// Converts a string representation to an `EmailAddress`. Panics when an error occurs.
63#[macro_export]
64macro_rules! email {
65    ($email:expr) => {{ $crate::smtp::address::EmailAddress::from_text($email).unwrap() }};
66}
67
68/// Converts a string representation to a `candid::Principal`. Panics when an error occurs.
69#[macro_export]
70macro_rules! principal {
71    ($id:expr) => {{ candid::Principal::from_text($id).unwrap() }};
72}
73
74#[doc(hidden)]
75pub use regex as __regex;
76
77/// Converts a string representation to a `regex::Regex`. Panics when an error occurs.
78/// Regex crate also has a regex! macro, but it returns a reference to a static value.
79#[macro_export]
80macro_rules! regex {
81    ($id:expr) => {{ $crate::__regex::Regex::new($id).unwrap() }};
82}
83
84/// tdb26-jop6k-aogll-7ltgs-eruif-6kk7m-qpktf-gdiqx-mxtrf-vb5e6-eqe
85pub const MAINNET_ROOT_SUBNET_ID: Principal = Principal::from_slice(&[
86    207, 242, 128, 227, 45, 127, 92, 205, 34, 70, 136, 47, 148, 175, 178, 15, 84, 202, 97, 162, 23,
87    101, 231, 18, 212, 61, 39, 137, 2,
88]);
89
90/// Generic error
91#[derive(thiserror::Error, Debug)]
92pub enum Error {
93    #[error(transparent)]
94    Generic(#[from] anyhow::Error),
95}
96
97/// Error to be used with `retry_async` macro
98/// which indicates whether it should be retried or not.
99#[derive(thiserror::Error, Debug)]
100pub enum RetryError {
101    #[error("Permanent error: {0:?}")]
102    Permanent(anyhow::Error),
103    #[error("Transient error: {0:?}")]
104    Transient(anyhow::Error),
105}
106
107/// Type of IC API request
108#[derive(
109    Debug,
110    Default,
111    Clone,
112    Copy,
113    Display,
114    PartialEq,
115    Eq,
116    PartialOrd,
117    Ord,
118    Hash,
119    IntoStaticStr,
120    EnumString,
121    Serialize,
122    Deserialize,
123)]
124#[strum(serialize_all = "snake_case")]
125#[serde(rename_all = "snake_case")]
126pub enum RequestType {
127    #[default]
128    Unknown,
129    Status,
130    QueryV2,
131    QueryV3,
132    QuerySubnetV3,
133    CallV2,
134    CallV3,
135    CallV4,
136    CallSubnetV4,
137    ReadStateV2,
138    ReadStateV3,
139    ReadStateSubnetV2,
140    ReadStateSubnetV3,
141}
142
143impl RequestType {
144    pub const fn is_query(&self) -> bool {
145        matches!(self, Self::QueryV2 | Self::QueryV3 | Self::QuerySubnetV3)
146    }
147
148    pub const fn is_call(&self) -> bool {
149        matches!(
150            self,
151            Self::CallV2 | Self::CallV3 | Self::CallV4 | Self::CallSubnetV4
152        )
153    }
154
155    pub const fn is_read_state(&self) -> bool {
156        matches!(
157            self,
158            Self::ReadStateV2
159                | Self::ReadStateV3
160                | Self::ReadStateSubnetV2
161                | Self::ReadStateSubnetV3
162        )
163    }
164}
165
166/// Parses size string as a binary (1k = 1024 etc) in u64
167pub fn parse_size(s: &str) -> Result<u64, parse_size::Error> {
168    parse_size::Config::new().with_binary().parse_size(s)
169}
170
171/// Parses size string as a binary (1k = 1024 etc) in usize
172pub fn parse_size_usize(s: &str) -> Result<usize, parse_size::Error> {
173    parse_size(s).map(|x| x as usize)
174}
175
176/// Parses size string as a decimal (1k = 1000 etc) in u64
177pub fn parse_size_decimal(s: &str) -> Result<u64, parse_size::Error> {
178    parse_size::Config::new().parse_size(s)
179}
180
181/// Parses size string as a decimal (1k = 1000 etc) in usize
182pub fn parse_size_decimal_usize(s: &str) -> Result<usize, parse_size::Error> {
183    parse_size_decimal(s).map(|x| x as usize)
184}
185
186/// Downloads the given url to given path.
187/// Destination folder must exist.
188pub fn download_url_to(url: &str, path: &Path) -> Result<u64, Error> {
189    let mut r = reqwest::blocking::get(url).context("unable to perform HTTP request")?;
190    if !r.status().is_success() {
191        return Err(anyhow!("incorrect HTTP code: {}", r.status()).into());
192    }
193
194    let mut file = File::create(path).context("could not create file")?;
195    Ok(r.copy_to(&mut file)
196        .context("unable to write body to file")?)
197}
198
199/// Downloads the given url and returns it as Bytes
200pub fn download_url(url: &str) -> Result<Bytes, Error> {
201    let r = reqwest::blocking::get(url).context("unable to perform HTTP request")?;
202    if !r.status().is_success() {
203        return Err(anyhow!("incorrect HTTP code: {}", r.status()).into());
204    }
205
206    Ok(r.bytes().context("unable to fetch file")?)
207}
208
209/// Downloads the given url to given path.
210/// Destination folder must exist.
211pub async fn download_url_to_async(url: &str, path: &Path) -> Result<(), Error> {
212    let r = reqwest::get(url)
213        .await
214        .context("unable to perform HTTP request")?;
215    if !r.status().is_success() {
216        return Err(anyhow!("incorrect HTTP code: {}", r.status()).into());
217    }
218
219    let mut file = tokio::fs::File::create(path)
220        .await
221        .context("could not create file")?;
222
223    let mut stream = r.bytes_stream();
224    while let Some(v) = stream.next().await {
225        file.write(&v.context("unable to read chunk")?)
226            .await
227            .context("unable to write chunk")?;
228    }
229
230    Ok(())
231}
232
233/// Downloads the given url and returns it as Bytes
234pub async fn download_url_async(url: &str) -> Result<Bytes, Error> {
235    let r = reqwest::get(url)
236        .await
237        .context("unable to perform HTTP request")?;
238
239    if !r.status().is_success() {
240        return Err(anyhow!("incorrect HTTP code: {}", r.status()).into());
241    }
242
243    Ok(r.bytes().await.context("unable to fetch file")?)
244}
245
246/// Retrying async closures/functions holding mutable references is a pain in Rust.
247/// So, for now, we'll have to use a macro to work that around.
248#[macro_export]
249macro_rules! retry_async {
250    ($f:expr, $timeout:expr, $delay:expr) => {{
251        use rand::{Rng, SeedableRng};
252        // SmallRng is Send which we require
253        let mut rng = rand::rngs::SmallRng::from_entropy();
254
255        let start = std::time::Instant::now();
256        let mut delay = $delay;
257
258        let result = loop {
259            // Bound this attempt by the *remaining* budget, not the original
260            // `$timeout` - otherwise a dependency that consistently takes
261            // just under `$timeout` before failing can make the loop's total
262            // wall-clock time run to several multiples of `$timeout`.
263            let attempt_timeout = $timeout.saturating_sub(start.elapsed());
264            if attempt_timeout == std::time::Duration::ZERO {
265                break Err(anyhow::anyhow!("Timed out"));
266            }
267
268            // Run the function wrapping it into Tokio timeout future so
269            // its execution time doesn't exceed our configured limit
270            let Ok(res) = tokio::time::timeout(attempt_timeout, $f).await else {
271                break Err(anyhow::anyhow!("Timed out"));
272            };
273
274            let err = match res {
275                Ok(v) => break Ok(v),
276                Err($crate::RetryError::Permanent(e)) => break Err(e),
277                Err($crate::RetryError::Transient(e)) => e,
278            };
279
280            let left = $timeout.saturating_sub(start.elapsed());
281            if left == std::time::Duration::ZERO {
282                break Err(err);
283            }
284
285            delay = left.min(delay * 2);
286            // Generate a random jitter in 0.0..0.1 range
287            let jitter: f64 = (rng.r#gen::<f64>() / 10.0);
288            let d64 = delay.as_secs_f64();
289            delay = Duration::from_secs_f64(d64.mul_add(0.95, d64 * jitter));
290            tokio::time::sleep(delay).await;
291        };
292
293        result
294    }};
295
296    ($f:expr, $timeout:expr) => {
297        retry_async!($f, $timeout, Duration::from_millis(500))
298    };
299
300    ($f:expr) => {
301        retry_async!($f, Duration::from_secs(60), Duration::from_millis(500))
302    };
303}
304
305/// Returns family of an IP address
306pub trait IpFamily {
307    fn family(&self) -> &'static str;
308}
309
310impl IpFamily for IpAddr {
311    fn family(&self) -> &'static str {
312        if self.is_ipv4() { "v4" } else { "v6" }
313    }
314}
315
316/// Converts bool to yes/no static str
317pub trait BoolYesNo {
318    fn yesno(&self) -> &'static str;
319}
320
321impl BoolYesNo for bool {
322    fn yesno(&self) -> &'static str {
323        if *self { "yes" } else { "no" }
324    }
325}
326
327pub trait SerializeOption<T> {
328    /// Serializes `Option<T>` as either inner value or provided default
329    fn serialize_or<'t, O>(&'t self, otherwise: O) -> SerializeOr<'t, T, O>;
330}
331
332pub struct SerializeOr<'t, T, O> {
333    option: &'t Option<T>,
334    otherwise: O,
335}
336
337impl<'t, T: Serialize, O: Serialize> Serialize for SerializeOr<'t, T, O> {
338    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
339    where
340        S: serde::Serializer,
341    {
342        match self.option {
343            Some(v) => v.serialize(serializer),
344            None => self.otherwise.serialize(serializer),
345        }
346    }
347}
348
349impl<T> SerializeOption<T> for Option<T> {
350    fn serialize_or<'t, O>(&'t self, otherwise: O) -> SerializeOr<'t, T, O> {
351        SerializeOr {
352            option: self,
353            otherwise,
354        }
355    }
356}
357
358#[macro_export]
359macro_rules! dyn_event {
360    ($lvl:ident, $($arg:tt)+) => {
361        match $lvl {
362            ::tracing::Level::TRACE => ::tracing::trace!($($arg)+),
363            ::tracing::Level::DEBUG => ::tracing::debug!($($arg)+),
364            ::tracing::Level::INFO => ::tracing::info!($($arg)+),
365            ::tracing::Level::WARN => ::tracing::warn!($($arg)+),
366            ::tracing::Level::ERROR => ::tracing::error!($($arg)+),
367        }
368    };
369}
370
371pub trait TruncatesString {
372    /// Truncates the given string to around n *bytes*,
373    /// on the closest UTF-8 code point boundary.
374    fn truncate_bytes(&self, n: usize) -> &str;
375}
376
377impl TruncatesString for &str {
378    fn truncate_bytes(&self, n: usize) -> &str {
379        truncate(self, n)
380    }
381}
382
383/// Truncates the given string to around n *bytes*,
384/// on the closest UTF-8 code point boundary.
385pub fn truncate(s: &str, n: usize) -> &str {
386    let n = s.len().min(n);
387    let m = (0..=n)
388        .rfind(|m| s.is_char_boundary(*m))
389        .unwrap_or_default();
390    &s[..m]
391}
392
393/// Best-effort (w/o assembly) constant-time comparison for byte slices
394pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
395    if a.len() != b.len() {
396        return false;
397    }
398
399    a.iter()
400        .zip(b.iter())
401        .fold(0u8, |acc, (x, y)| acc | (x ^ y))
402        == 0
403}
404
405/// Implements display for Duration
406pub trait DurationDisplay<'a> {
407    /// Implements Display for Duration in a human-friendly format
408    fn display(&self) -> DisplayDuration;
409}
410
411/// Displays Duration in a human-friendly format
412pub struct DisplayDuration(Duration);
413
414impl DurationDisplay<'_> for Duration {
415    fn display(&self) -> DisplayDuration {
416        DisplayDuration(*self)
417    }
418}
419
420impl Display for DisplayDuration {
421    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
422        let mut secs = self.0.as_secs();
423        // If the duration is shorter than a second - use a distinct approach
424        if secs == 0 {
425            let nanos = self.0.as_nanos();
426            if nanos < 1000 {
427                return write!(f, "{nanos}ns");
428            }
429
430            let micros = self.0.as_micros();
431            if micros < 1000 {
432                return write!(f, "{micros}us");
433            }
434
435            return write!(f, "{}ms", self.0.as_millis());
436        }
437
438        // If the duration is shorter than a minute,
439        // use seconds with a fractional part.
440        // Truncate (rather than round) the fraction so that e.g. 59.999s
441        // doesn't get displayed as "60.00s".
442        if secs < 60 {
443            let hundredths = self.0.subsec_millis() / 10;
444            return write!(f, "{secs}.{hundredths:02}s");
445        }
446
447        // Average year is 365.24 days...
448        let years = secs / 365 / 86400;
449        if years > 0 {
450            secs -= years * 86400 * 365;
451            write!(f, "{years}y")?;
452        }
453
454        let days = secs / 86400;
455        if days > 0 {
456            secs -= days * 86400;
457            write!(f, "{days}d")?;
458        }
459
460        let hours = secs / 3600;
461        if hours > 0 {
462            secs -= hours * 3600;
463            write!(f, "{hours}h")?;
464        }
465
466        let mins = secs / 60;
467        if mins > 0 {
468            secs -= mins * 60;
469            write!(f, "{mins}m")?;
470        }
471
472        if secs > 0 {
473            write!(f, "{secs}s")?;
474        }
475
476        Ok(())
477    }
478}
479
480#[cfg(test)]
481mod test {
482    use super::*;
483
484    #[test]
485    fn test_truncate() {
486        assert_eq!(truncate("foobarbaz", 4), "foob");
487        assert_eq!(truncate("tättähäärä härkä", 12), "tättähää");
488        assert_eq!(truncate("", 99), "");
489        assert_eq!(truncate("🏁", 2), "");
490        assert_eq!(truncate("foobarbaz", 99), "foobarbaz");
491
492        assert_eq!("tättähäärä härkä".truncate_bytes(12), "tättähää");
493    }
494
495    #[tokio::test]
496    async fn test_retry_async_bounds_total_time_to_timeout() {
497        use std::time::Duration;
498
499        let timeout = Duration::from_millis(300);
500        let base_delay = Duration::from_millis(20);
501        let attempt_duration = Duration::from_millis(200);
502
503        let start = std::time::Instant::now();
504        let result: Result<(), anyhow::Error> = retry_async! {
505            async {
506                tokio::time::sleep(attempt_duration).await;
507                Err::<(), _>(RetryError::Transient(anyhow::anyhow!("always fails")))
508            },
509            timeout,
510            base_delay
511        };
512        let elapsed = start.elapsed();
513
514        assert!(result.is_err());
515        // Each attempt (200ms) comfortably fits within the overall timeout
516        // (300ms) on its own, so a per-attempt timeout that isn't shrunk to
517        // the remaining budget lets a second full attempt run past the
518        // deadline (previously observed ~440ms total here instead of
519        // staying close to the configured 300ms).
520        assert!(
521            elapsed < timeout + Duration::from_millis(100),
522            "retry_async! ran for {elapsed:?}, expected to stay close to the {timeout:?} budget"
523        );
524    }
525
526    #[test]
527    fn test_constant_time_eq() {
528        assert!(constant_time_eq(b"foo", b"foo"));
529        assert!(!constant_time_eq(b"foo", b"bar"));
530        assert!(!constant_time_eq(b"foobar", b"bar"));
531    }
532
533    #[test]
534    fn test_duration_display() {
535        assert_eq!(
536            Duration::from_secs(31626061).display().to_string(),
537            "1y1d1h1m1s"
538        );
539        assert_eq!(Duration::from_hours(72).display().to_string(), "3d");
540        assert_eq!(Duration::from_hours(80).display().to_string(), "3d8h");
541        assert_eq!(Duration::from_mins(4812).display().to_string(), "3d8h12m");
542        assert_eq!(
543            Duration::from_secs(288735).display().to_string(),
544            "3d8h12m15s"
545        );
546        assert_eq!(
547            Duration::from_millis(288735123).display().to_string(),
548            "3d8h12m15s"
549        );
550
551        // Sub-second formatting
552        assert_eq!(Duration::ZERO.display().to_string(), "0ns");
553        assert_eq!(Duration::from_nanos(999).display().to_string(), "999ns");
554        assert_eq!(Duration::from_micros(1).display().to_string(), "1us");
555        assert_eq!(Duration::from_micros(999).display().to_string(), "999us");
556        // Exactly 1000us should roll over to the ms branch, not stay "1000us"
557        assert_eq!(Duration::from_micros(1000).display().to_string(), "1ms");
558        assert_eq!(Duration::from_millis(1).display().to_string(), "1ms");
559        assert_eq!(Duration::from_millis(999).display().to_string(), "999ms");
560
561        // Sub-minute fractional seconds
562        assert_eq!(Duration::from_millis(1001).display().to_string(), "1.00s");
563        assert_eq!(Duration::from_millis(59494).display().to_string(), "59.49s");
564        assert_eq!(Duration::from_millis(59999).display().to_string(), "59.99s");
565
566        // Minute/hour/day/year boundaries, exact and with skipped middle units
567        assert_eq!(Duration::from_millis(60001).display().to_string(), "1m");
568        assert_eq!(Duration::from_secs(60).display().to_string(), "1m");
569        assert_eq!(Duration::from_secs(3600).display().to_string(), "1h");
570        assert_eq!(Duration::from_secs(3605).display().to_string(), "1h5s");
571        assert_eq!(Duration::from_secs(86400).display().to_string(), "1d");
572        assert_eq!(Duration::from_secs(86400 + 5).display().to_string(), "1d5s");
573        assert_eq!(Duration::from_secs(365 * 86400).display().to_string(), "1y");
574    }
575}