Skip to main content

hydro_lang/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![cfg_attr(not(stageleft_trybuild), warn(missing_docs))]
3
4//! Hydro is a high-level distributed programming framework for Rust.
5//! Hydro can help you quickly write scalable distributed services that are correct by construction.
6//! Much like Rust helps with memory safety, Hydro helps with [distributed safety](https://hydro.run/docs/hydro/reference/correctness/).
7//!
8//! The core Hydro API involves [live collections](https://hydro.run/docs/hydro/reference/introduction/live-collections), which represent asynchronously
9//! updated sources of data such as incoming network requests and application state. The most common live collection is
10//! [`live_collections::stream::Stream`]; other live collections can be found in [`live_collections`].
11//!
12//! Hydro uses a unique compilation approach where you define deployment logic as Rust code alongside your distributed system implementation.
13//! For more details on this API, see the [Hydro docs](https://hydro.run/docs/hydro/reference/deploy/) and the [`deploy`] module.
14
15stageleft::stageleft_no_entry_crate!();
16
17#[cfg(feature = "runtime_support")]
18#[cfg_attr(docsrs, doc(cfg(feature = "runtime_support")))]
19#[doc(hidden)]
20pub mod runtime_support {
21    pub use ::{bincode, dfir_rs, slotmap, stageleft};
22    #[cfg(feature = "sim")]
23    pub use colored;
24    #[cfg(feature = "deploy_integration")]
25    pub use hydro_deploy_integration;
26    #[cfg(feature = "tokio")]
27    pub use tokio;
28
29    #[cfg(feature = "deploy_integration")]
30    pub mod launch;
31}
32
33#[doc(hidden)]
34pub mod macro_support {
35    pub use copy_span;
36    #[cfg(feature = "trybuild")]
37    pub use ctor;
38}
39
40pub mod prelude {
41    // taken from `tokio`
42    //! A "prelude" for users of the `hydro_lang` crate.
43    //!
44    //! This prelude is similar to the standard library's prelude in that you'll almost always want to import its entire contents, but unlike the standard library's prelude you'll have to do so manually:
45    //! ```
46    //! # #![allow(warnings)]
47    //! use hydro_lang::prelude::*;
48    //! ```
49    //!
50    //! The prelude may grow over time as additional items see ubiquitous use.
51
52    pub use stageleft::q;
53
54    pub use crate::compile::builder::FlowBuilder;
55    pub use crate::live_collections::boundedness::{Bounded, Unbounded};
56    pub use crate::live_collections::keyed_singleton::{KeyedSingleton, MonotonicKeys};
57    pub use crate::live_collections::keyed_stream::KeyedStream;
58    pub use crate::live_collections::optional::{InitNone, Optional};
59    pub use crate::live_collections::singleton::Singleton;
60    pub use crate::live_collections::sliced::sliced;
61    pub use crate::live_collections::stream::Stream;
62    pub use crate::location::{Cluster, External, Location as _, Process, Tick};
63    pub use crate::networking::{EMBEDDED, TCP, UDP};
64    pub use crate::nondet::{NonDet, nondet};
65    pub use crate::properties::{
66        ConsistencyProof, ManualProof, VerusCommutativeProof, VerusIdempotentProof,
67        VerusMonotoneProof, VerusOrderPreservingProof, manual_proof, verus_panic,
68        verus_proof_commutative_effect, verus_proof_commutative_filter,
69        verus_proof_commutative_fold, verus_proof_commutative_map, verus_proof_idempotent_effect,
70        verus_proof_idempotent_filter, verus_proof_idempotent_fold, verus_proof_idempotent_map,
71        verus_proof_idempotent_reduce, verus_proof_monotone_fold, verus_proof_order_preserving_map,
72    };
73
74    #[cfg(feature = "trybuild")]
75    /// A macro to set up a Hydro crate.
76    #[macro_export]
77    macro_rules! setup {
78        () => {
79            stageleft::stageleft_no_entry_crate!();
80
81            #[cfg(test)]
82            mod test_init {
83                $crate::macro_support::ctor::declarative::ctor!(
84                    #[ctor(unsafe)]
85                    fn init() {
86                        $crate::compile::init_test();
87                    }
88                );
89            }
90        };
91    }
92
93    #[cfg(not(feature = "trybuild"))]
94    /// A macro to set up a Hydro crate.
95    #[macro_export]
96    macro_rules! setup {
97        () => {
98            stageleft::stageleft_no_entry_crate!();
99        };
100    }
101}
102
103#[cfg(feature = "dfir_context")]
104#[cfg_attr(docsrs, doc(cfg(feature = "dfir_context")))]
105pub mod runtime_context;
106
107pub mod nondet;
108
109pub mod live_collections;
110
111pub mod location;
112
113pub mod networking;
114
115pub mod properties;
116
117pub mod telemetry;
118
119#[cfg(any(
120    feature = "deploy",
121    feature = "sim",
122    feature = "deploy_integration" // hidden internal feature enabled in the trybuild
123))]
124#[cfg_attr(docsrs, doc(cfg(any(feature = "deploy", feature = "sim"))))]
125pub mod deploy;
126
127#[cfg(feature = "sim")]
128#[cfg_attr(docsrs, doc(cfg(feature = "sim")))]
129pub mod sim;
130
131pub mod sim_hooks;
132
133pub mod forward_handle;
134
135pub mod compile;
136
137pub mod handoff_ref;
138
139mod manual_expr;
140
141#[cfg(stageleft_runtime)]
142#[cfg(feature = "viz")]
143#[cfg_attr(docsrs, doc(cfg(feature = "viz")))]
144#[expect(missing_docs, reason = "TODO")]
145pub mod viz;
146
147#[cfg_attr(
148    feature = "stageleft_macro_entrypoint",
149    expect(missing_docs, reason = "staging internals")
150)]
151mod staging_util;
152
153#[cfg(feature = "deploy")]
154#[cfg_attr(docsrs, doc(cfg(feature = "deploy")))]
155pub mod test_util;
156
157#[cfg(feature = "build")]
158ctor::declarative::ctor!(
159    #[ctor(unsafe)]
160    fn init_rewrites() {
161        stageleft::add_private_reexport(
162            vec!["tokio_util", "codec", "lines_codec"],
163            vec!["tokio_util", "codec"],
164        );
165        // TODO: remove once stabilized
166        stageleft::add_private_reexport(
167            vec!["core", "io", "error", "Error"],
168            vec!["std", "io", "Error"],
169        );
170        // Nightly moved `Rc`/`Arc` (and their `Weak`s) into a private `alloc::rcs` module, so
171        // `type_name` reports `alloc::rcs::rc::Rc` / `alloc::rcs::arc::Arc`. Stageleft's
172        // built-in `alloc -> std` rule runs first and recurses, so match the rewritten form.
173        // TODO: remove once stageleft ships these rules (or the paths stabilize).
174        #[cfg(nightly)]
175        {
176            stageleft::add_private_reexport(vec!["std", "rcs", "rc"], vec!["std", "rc"]);
177            stageleft::add_private_reexport(vec!["std", "rcs", "arc"], vec!["std", "sync"]);
178        }
179    }
180);
181
182#[cfg(all(test, feature = "trybuild"))]
183mod test_init {
184    ctor::declarative::ctor!(
185        #[ctor(unsafe)]
186        fn init() {
187            crate::compile::init_test();
188            // Install a tracing subscriber so diagnostics (e.g. the `hydro_build` build-timing
189            // events used by scripts/bench_trybuild.sh) can be enabled via RUST_LOG.
190            crate::telemetry::initialize_tracing();
191        }
192    );
193}
194
195/// Creates a newtype wrapper around an integer type.
196///
197/// Usage:
198/// ```rust,ignore
199/// hydro_lang::newtype_counter! {
200///     /// My counter.
201///     pub struct MyCounter(u32);
202///
203///     /// My secret counter.
204///     struct SecretCounter(u64);
205/// }
206/// ```
207#[doc(hidden)]
208#[macro_export]
209macro_rules! newtype_counter {
210    (
211        $(
212            $( #[$attr:meta] )*
213            $vis:vis struct $name:ident($typ:ty);
214        )*
215    ) => {
216        $(
217            $( #[$attr] )*
218            #[repr(transparent)]
219            #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
220            $vis struct $name($typ);
221
222            #[allow(clippy::allow_attributes, dead_code, reason = "macro-generated methods may be unused")]
223            impl $name {
224                /// Reveals the inner ID.
225                pub fn into_inner(self) -> $typ {
226                    self.0
227                }
228            }
229
230            impl std::fmt::Display for $name {
231                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232                    write!(f, "{}", self.0)
233                }
234            }
235
236            impl serde::ser::Serialize for $name {
237                fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
238                where
239                    S: serde::Serializer
240                {
241                    serde::ser::Serialize::serialize(&self.0, serializer)
242                }
243            }
244
245            impl<'de> serde::de::Deserialize<'de> for $name {
246                fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
247                where
248                    D: serde::Deserializer<'de>
249                {
250                    serde::de::Deserialize::deserialize(deserializer).map(Self)
251                }
252            }
253
254            #[sealed::sealed]
255            impl $crate::Countable for $name {
256                fn from_count(val: usize) -> Self {
257                    Self(val as $typ)
258                }
259            }
260        )*
261    };
262}
263
264/// Sealed trait implemented by ID types produced via [`newtype_counter!`].
265///
266/// This allows [`Counter<T>`] to mint new IDs without exposing a public
267/// constructor on the ID types themselves.
268#[doc(hidden)]
269#[sealed::sealed]
270pub trait Countable {
271    #[doc(hidden)]
272    fn from_count(val: usize) -> Self;
273}
274
275/// An opaque counter that produces unique IDs of type `T` via [`Counter::get_and_increment`].
276///
277/// This is separate from the ID types themselves so that holding an ID does not
278/// give the ability to mint new IDs.
279#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
280pub struct Counter<T: Countable>(usize, std::marker::PhantomData<T>);
281
282impl<T: Countable> Default for Counter<T> {
283    fn default() -> Self {
284        Self(0, std::marker::PhantomData)
285    }
286}
287
288impl<T: Countable> Counter<T> {
289    /// Gets the current counter value and increments for the next call.
290    pub fn get_and_increment(&mut self) -> T {
291        let id = self.0;
292        self.0 += 1;
293        T::from_count(id)
294    }
295
296    /// Returns an iterator from zero up to (but excluding) the current counter value.
297    ///
298    /// This is useful for iterating already-allocated values.
299    pub fn range_up_to(&self) -> impl DoubleEndedIterator<Item = T> + std::iter::FusedIterator {
300        (0..self.0).map(T::from_count)
301    }
302}