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