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