Skip to main content

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