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