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::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::{TCP, UDP};
64    pub use crate::nondet::{NonDet, nondet};
65    pub use crate::properties::{ConsistencyProof, ManualProof, manual_proof};
66
67    #[cfg(feature = "trybuild")]
68    /// A macro to set up a Hydro crate.
69    #[macro_export]
70    macro_rules! setup {
71        () => {
72            stageleft::stageleft_no_entry_crate!();
73
74            #[cfg(test)]
75            mod test_init {
76                $crate::macro_support::ctor::declarative::ctor!(
77                    #[ctor(unsafe)]
78                    fn init() {
79                        $crate::compile::init_test();
80                    }
81                );
82            }
83        };
84    }
85
86    #[cfg(not(feature = "trybuild"))]
87    /// A macro to set up a Hydro crate.
88    #[macro_export]
89    macro_rules! setup {
90        () => {
91            stageleft::stageleft_no_entry_crate!();
92        };
93    }
94}
95
96#[cfg(feature = "dfir_context")]
97#[cfg_attr(docsrs, doc(cfg(feature = "dfir_context")))]
98pub mod runtime_context;
99
100pub mod nondet;
101
102pub mod live_collections;
103
104pub mod location;
105
106pub mod networking;
107
108pub mod properties;
109
110pub mod telemetry;
111
112#[cfg(any(
113    feature = "deploy",
114    feature = "sim",
115    feature = "deploy_integration" // hidden internal feature enabled in the trybuild
116))]
117#[cfg_attr(docsrs, doc(cfg(any(feature = "deploy", feature = "sim"))))]
118pub mod deploy;
119
120#[cfg(feature = "sim")]
121#[cfg_attr(docsrs, doc(cfg(feature = "sim")))]
122pub mod sim;
123
124pub mod forward_handle;
125
126pub mod compile;
127
128pub mod handoff_ref;
129
130mod manual_expr;
131
132#[cfg(stageleft_runtime)]
133#[cfg(feature = "viz")]
134#[cfg_attr(docsrs, doc(cfg(feature = "viz")))]
135#[expect(missing_docs, reason = "TODO")]
136pub mod viz;
137
138#[cfg_attr(
139    feature = "stageleft_macro_entrypoint",
140    expect(missing_docs, reason = "staging internals")
141)]
142mod staging_util;
143
144#[cfg(feature = "deploy")]
145#[cfg_attr(docsrs, doc(cfg(feature = "deploy")))]
146pub mod test_util;
147
148#[cfg(feature = "build")]
149ctor::declarative::ctor!(
150    #[ctor(unsafe)]
151    fn init_rewrites() {
152        stageleft::add_private_reexport(
153            vec!["tokio_util", "codec", "lines_codec"],
154            vec!["tokio_util", "codec"],
155        );
156        // TODO: remove once stabilized
157        stageleft::add_private_reexport(
158            vec!["core", "io", "error", "Error"],
159            vec!["std", "io", "Error"],
160        );
161    }
162);
163
164#[cfg(all(test, feature = "trybuild"))]
165mod test_init {
166    ctor::declarative::ctor!(
167        #[ctor(unsafe)]
168        fn init() {
169            crate::compile::init_test();
170            // Install a tracing subscriber so diagnostics (e.g. the `hydro_build` build-timing
171            // events used by scripts/bench_trybuild.sh) can be enabled via RUST_LOG.
172            crate::telemetry::initialize_tracing();
173        }
174    );
175}
176
177/// Creates a newtype wrapper around an integer type.
178///
179/// Usage:
180/// ```rust,ignore
181/// hydro_lang::newtype_counter! {
182///     /// My counter.
183///     pub struct MyCounter(u32);
184///
185///     /// My secret counter.
186///     struct SecretCounter(u64);
187/// }
188/// ```
189#[doc(hidden)]
190#[macro_export]
191macro_rules! newtype_counter {
192    (
193        $(
194            $( #[$attr:meta] )*
195            $vis:vis struct $name:ident($typ:ty);
196        )*
197    ) => {
198        $(
199            $( #[$attr] )*
200            #[repr(transparent)]
201            #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
202            $vis struct $name($typ);
203
204            #[allow(clippy::allow_attributes, dead_code, reason = "macro-generated methods may be unused")]
205            impl $name {
206                /// Reveals the inner ID.
207                pub fn into_inner(self) -> $typ {
208                    self.0
209                }
210            }
211
212            impl std::fmt::Display for $name {
213                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
214                    write!(f, "{}", self.0)
215                }
216            }
217
218            impl serde::ser::Serialize for $name {
219                fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
220                where
221                    S: serde::Serializer
222                {
223                    serde::ser::Serialize::serialize(&self.0, serializer)
224                }
225            }
226
227            impl<'de> serde::de::Deserialize<'de> for $name {
228                fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
229                where
230                    D: serde::Deserializer<'de>
231                {
232                    serde::de::Deserialize::deserialize(deserializer).map(Self)
233                }
234            }
235
236            #[sealed::sealed]
237            impl $crate::Countable for $name {
238                fn from_count(val: usize) -> Self {
239                    Self(val as $typ)
240                }
241            }
242        )*
243    };
244}
245
246/// Sealed trait implemented by ID types produced via [`newtype_counter!`].
247///
248/// This allows [`Counter<T>`] to mint new IDs without exposing a public
249/// constructor on the ID types themselves.
250#[doc(hidden)]
251#[sealed::sealed]
252pub trait Countable {
253    #[doc(hidden)]
254    fn from_count(val: usize) -> Self;
255}
256
257/// An opaque counter that produces unique IDs of type `T` via [`Counter::get_and_increment`].
258///
259/// This is separate from the ID types themselves so that holding an ID does not
260/// give the ability to mint new IDs.
261#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
262pub struct Counter<T: Countable>(usize, std::marker::PhantomData<T>);
263
264impl<T: Countable> Default for Counter<T> {
265    fn default() -> Self {
266        Self(0, std::marker::PhantomData)
267    }
268}
269
270impl<T: Countable> Counter<T> {
271    /// Gets the current counter value and increments for the next call.
272    pub fn get_and_increment(&mut self) -> T {
273        let id = self.0;
274        self.0 += 1;
275        T::from_count(id)
276    }
277
278    /// Returns an iterator from zero up to (but excluding) the current counter value.
279    ///
280    /// This is useful for iterating already-allocated values.
281    pub fn range_up_to(&self) -> impl DoubleEndedIterator<Item = T> + std::iter::FusedIterator {
282        (0..self.0).map(T::from_count)
283    }
284}