1#![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#![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#[macro_export]
64macro_rules! email {
65 ($email:expr) => {{ $crate::smtp::address::EmailAddress::from_text($email).unwrap() }};
66}
67
68#[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#[macro_export]
80macro_rules! regex {
81 ($id:expr) => {{ $crate::__regex::Regex::new($id).unwrap() }};
82}
83
84pub 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#[derive(thiserror::Error, Debug)]
92pub enum Error {
93 #[error(transparent)]
94 Generic(#[from] anyhow::Error),
95}
96
97#[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#[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
166pub fn parse_size(s: &str) -> Result<u64, parse_size::Error> {
168 parse_size::Config::new().with_binary().parse_size(s)
169}
170
171pub fn parse_size_usize(s: &str) -> Result<usize, parse_size::Error> {
173 parse_size(s).map(|x| x as usize)
174}
175
176pub fn parse_size_decimal(s: &str) -> Result<u64, parse_size::Error> {
178 parse_size::Config::new().parse_size(s)
179}
180
181pub fn parse_size_decimal_usize(s: &str) -> Result<usize, parse_size::Error> {
183 parse_size_decimal(s).map(|x| x as usize)
184}
185
186pub 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
199pub 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
209pub 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
233pub 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#[macro_export]
249macro_rules! retry_async {
250 ($f:expr, $timeout:expr, $delay:expr) => {{
251 use rand::{Rng, SeedableRng};
252 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 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 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 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
305pub 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
316pub 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 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 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
383pub 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
393pub 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
405pub trait DurationDisplay<'a> {
407 fn display(&self) -> DisplayDuration;
409}
410
411pub 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 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 secs < 60 {
443 let hundredths = self.0.subsec_millis() / 10;
444 return write!(f, "{secs}.{hundredths:02}s");
445 }
446
447 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 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 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 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 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 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}