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