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