linera_base/
lib.rs

1// Copyright (c) Zefchain Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! This module provides a common set of types and library functions that are shared
5//! between the Linera protocol (compiled from Rust to native code) and Linera
6//! applications (compiled from Rust to Wasm).
7
8#![deny(missing_docs)]
9#![deny(clippy::large_futures)]
10#![allow(async_fn_in_trait)]
11
12use std::fmt;
13
14#[doc(hidden)]
15pub use async_trait::async_trait;
16#[cfg(all(not(target_arch = "wasm32"), unix))]
17use tokio::signal::unix;
18#[cfg(not(target_arch = "wasm32"))]
19use {::tracing::debug, tokio_util::sync::CancellationToken};
20pub mod abi;
21#[cfg(not(target_arch = "wasm32"))]
22pub mod command;
23pub mod crypto;
24pub mod data_types;
25pub mod dyn_convert;
26mod graphql;
27pub mod hashed;
28pub mod http;
29pub mod identifiers;
30mod limited_writer;
31pub mod ownership;
32#[cfg(not(target_arch = "wasm32"))]
33pub mod port;
34#[cfg(with_metrics)]
35pub mod prometheus_util;
36#[cfg(not(chain))]
37pub mod task;
38pub mod vm;
39#[cfg(not(chain))]
40pub use task::Blocking;
41pub mod time;
42#[cfg_attr(web, path = "tracing_web.rs")]
43pub mod tracing;
44#[cfg(test)]
45mod unit_tests;
46
47pub use graphql::BcsHexParseError;
48#[doc(hidden)]
49pub use {async_graphql, bcs, hex};
50
51/// A macro for asserting that a condition is true, returning an error if it is not.
52///
53/// # Examples
54///
55/// ```
56/// # use linera_base::ensure;
57/// fn divide(x: i32, y: i32) -> Result<i32, String> {
58///     ensure!(y != 0, "division by zero");
59///     Ok(x / y)
60/// }
61///
62/// assert_eq!(divide(10, 2), Ok(5));
63/// assert_eq!(divide(10, 0), Err(String::from("division by zero")));
64/// ```
65#[macro_export]
66macro_rules! ensure {
67    ($cond:expr, $e:expr) => {
68        if !($cond) {
69            return Err($e.into());
70        }
71    };
72}
73
74/// Formats a byte sequence as a hexadecimal string, and elides bytes in the middle if it is longer
75/// than 32 bytes.
76///
77/// This function is intended to be used with the `#[debug(with = "hex_debug")]` field
78/// annotation of `custom_debug_derive::Debug`.
79///
80/// # Examples
81///
82/// ```
83/// # use linera_base::hex_debug;
84/// use custom_debug_derive::Debug;
85///
86/// #[derive(Debug)]
87/// struct Message {
88///     #[debug(with = "hex_debug")]
89///     bytes: Vec<u8>,
90/// }
91///
92/// let msg = Message {
93///     bytes: vec![0x12, 0x34, 0x56, 0x78],
94/// };
95///
96/// assert_eq!(format!("{:?}", msg), "Message { bytes: 12345678 }");
97///
98/// let long_msg = Message {
99///     bytes: b"        10        20        30        40        50".to_vec(),
100/// };
101///
102/// assert_eq!(
103///     format!("{:?}", long_msg),
104///     "Message { bytes: 20202020202020203130202020202020..20202020343020202020202020203530 }"
105/// );
106/// ```
107pub fn hex_debug<T: AsRef<[u8]>>(bytes: &T, f: &mut fmt::Formatter) -> fmt::Result {
108    const ELIDE_AFTER: usize = 16;
109    let bytes = bytes.as_ref();
110    if bytes.len() <= 2 * ELIDE_AFTER {
111        write!(f, "{}", hex::encode(bytes))?;
112    } else {
113        write!(
114            f,
115            "{}..{}",
116            hex::encode(&bytes[..ELIDE_AFTER]),
117            hex::encode(&bytes[(bytes.len() - ELIDE_AFTER)..])
118        )?;
119    }
120    Ok(())
121}
122
123/// Applies `hex_debug` to a slice of byte vectors.
124///
125///  # Examples
126///
127/// ```
128/// # use linera_base::hex_vec_debug;
129/// use custom_debug_derive::Debug;
130///
131/// #[derive(Debug)]
132/// struct Messages {
133///     #[debug(with = "hex_vec_debug")]
134///     byte_vecs: Vec<Vec<u8>>,
135/// }
136///
137/// let msgs = Messages {
138///     byte_vecs: vec![vec![0x12, 0x34, 0x56, 0x78], vec![0x9A]],
139/// };
140///
141/// assert_eq!(
142///     format!("{:?}", msgs),
143///     "Messages { byte_vecs: [12345678, 9a] }"
144/// );
145/// ```
146#[expect(clippy::ptr_arg)] // This only works with custom_debug_derive if it's &Vec.
147pub fn hex_vec_debug(list: &Vec<Vec<u8>>, f: &mut fmt::Formatter) -> fmt::Result {
148    write!(f, "[")?;
149    for (i, bytes) in list.iter().enumerate() {
150        if i != 0 {
151            write!(f, ", ")?;
152        }
153        hex_debug(bytes, f)?;
154    }
155    write!(f, "]")
156}
157
158/// Listens for shutdown signals, and notifies the [`CancellationToken`] if one is
159/// received.
160#[cfg(not(target_arch = "wasm32"))]
161pub async fn listen_for_shutdown_signals(shutdown_sender: CancellationToken) {
162    let _shutdown_guard = shutdown_sender.drop_guard();
163
164    #[cfg(unix)]
165    {
166        let mut sigint =
167            unix::signal(unix::SignalKind::interrupt()).expect("Failed to set up SIGINT handler");
168        let mut sigterm =
169            unix::signal(unix::SignalKind::terminate()).expect("Failed to set up SIGTERM handler");
170        let mut sighup =
171            unix::signal(unix::SignalKind::hangup()).expect("Failed to set up SIGHUP handler");
172
173        tokio::select! {
174            _ = sigint.recv() => debug!("Received SIGINT"),
175            _ = sigterm.recv() => debug!("Received SIGTERM"),
176            _ = sighup.recv() => debug!("Received SIGHUP"),
177        }
178    }
179
180    #[cfg(windows)]
181    {
182        tokio::signal::ctrl_c()
183            .await
184            .expect("Failed to set up Ctrl+C handler");
185        debug!("Received Ctrl+C");
186    }
187}