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