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 vm;
38#[cfg(not(chain))]
39pub use task::Blocking;
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;
47
48pub use graphql::BcsHexParseError;
49#[doc(hidden)]
50pub use {async_graphql, bcs, hex};
51
52/// A macro for asserting that a condition is true, returning an error if it is not.
53///
54/// # Examples
55///
56/// ```
57/// # use linera_base::ensure;
58/// fn divide(x: i32, y: i32) -> Result<i32, String> {
59/// ensure!(y != 0, "division by zero");
60/// Ok(x / y)
61/// }
62///
63/// assert_eq!(divide(10, 2), Ok(5));
64/// assert_eq!(divide(10, 0), Err(String::from("division by zero")));
65/// ```
66#[macro_export]
67macro_rules! ensure {
68 ($cond:expr, $e:expr) => {
69 if !($cond) {
70 return Err($e.into());
71 }
72 };
73}
74
75/// Formats a byte sequence as a hexadecimal string, and elides bytes in the middle if it is longer
76/// than 32 bytes.
77///
78/// This function is intended to be used with the `#[debug(with = "hex_debug")]` field
79/// annotation of `custom_debug_derive::Debug`.
80///
81/// # Examples
82///
83/// ```
84/// # use linera_base::hex_debug;
85/// use custom_debug_derive::Debug;
86///
87/// #[derive(Debug)]
88/// struct Message {
89/// #[debug(with = "hex_debug")]
90/// bytes: Vec<u8>,
91/// }
92///
93/// let msg = Message {
94/// bytes: vec![0x12, 0x34, 0x56, 0x78],
95/// };
96///
97/// assert_eq!(format!("{:?}", msg), "Message { bytes: 12345678 }");
98///
99/// let long_msg = Message {
100/// bytes: b" 10 20 30 40 50".to_vec(),
101/// };
102///
103/// assert_eq!(
104/// format!("{:?}", long_msg),
105/// "Message { bytes: 20202020202020203130202020202020..20202020343020202020202020203530 }"
106/// );
107/// ```
108pub fn hex_debug<T: AsRef<[u8]>>(bytes: &T, f: &mut fmt::Formatter) -> fmt::Result {
109 const ELIDE_AFTER: usize = 16;
110 let bytes = bytes.as_ref();
111 if bytes.len() <= 2 * ELIDE_AFTER {
112 write!(f, "{}", hex::encode(bytes))?;
113 } else {
114 write!(
115 f,
116 "{}..{}",
117 hex::encode(&bytes[..ELIDE_AFTER]),
118 hex::encode(&bytes[(bytes.len() - ELIDE_AFTER)..])
119 )?;
120 }
121 Ok(())
122}
123
124/// Applies `hex_debug` to a slice of byte vectors.
125///
126/// # Examples
127///
128/// ```
129/// # use linera_base::hex_vec_debug;
130/// use custom_debug_derive::Debug;
131///
132/// #[derive(Debug)]
133/// struct Messages {
134/// #[debug(with = "hex_vec_debug")]
135/// byte_vecs: Vec<Vec<u8>>,
136/// }
137///
138/// let msgs = Messages {
139/// byte_vecs: vec![vec![0x12, 0x34, 0x56, 0x78], vec![0x9A]],
140/// };
141///
142/// assert_eq!(
143/// format!("{:?}", msgs),
144/// "Messages { byte_vecs: [12345678, 9a] }"
145/// );
146/// ```
147#[expect(clippy::ptr_arg)] // This only works with custom_debug_derive if it's &Vec.
148pub fn hex_vec_debug(list: &Vec<Vec<u8>>, f: &mut fmt::Formatter) -> fmt::Result {
149 write!(f, "[")?;
150 for (i, bytes) in list.iter().enumerate() {
151 if i != 0 {
152 write!(f, ", ")?;
153 }
154 hex_debug(bytes, f)?;
155 }
156 write!(f, "]")
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}