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