hydro_lang/
runtime_context.rs

1//! Interfaces to access DFIR runtime metadata from Hydro programs.
2
3use dfir_rs::scheduled::context::Context;
4use quote::quote;
5use stageleft::runtime_support::{FreeVariableWithContext, QuoteTokens};
6
7use crate::location::Location;
8
9/// Exposes the DFIR [`Context`] inside quoted code.
10pub static RUNTIME_CONTEXT: RuntimeContext = RuntimeContext { _private: &() };
11
12/// A handle to DFIR [`Context`] which can be used inside quoted code.
13///
14/// When spliced, it turns into a reference to [`Context`].
15#[derive(Clone, Copy)]
16pub struct RuntimeContext<'a> {
17    _private: &'a (),
18}
19
20impl<'a, L> FreeVariableWithContext<L> for RuntimeContext<'a>
21where
22    L: Location<'a>,
23{
24    type O = &'a Context;
25
26    fn to_tokens(self, _ctx: &L) -> QuoteTokens {
27        QuoteTokens {
28            prelude: None,
29            expr: Some(quote!(&context)),
30        }
31    }
32}
33
34#[cfg(test)]
35mod tests {
36    use futures::StreamExt;
37    use hydro_deploy::Deployment;
38    use stageleft::q;
39
40    use super::RUNTIME_CONTEXT;
41    use crate::builder::FlowBuilder;
42    use crate::location::Location;
43
44    struct P1 {}
45
46    #[tokio::test]
47    async fn runtime_context() {
48        let mut deployment = Deployment::new();
49
50        let flow = FlowBuilder::new();
51        let node = flow.process::<P1>();
52        let external = flow.external::<()>();
53
54        let out_port = node
55            .source_iter(q!(0..5))
56            .map(q!(|v| (v, RUNTIME_CONTEXT.current_tick().0)))
57            .send_bincode_external(&external);
58
59        let nodes = flow
60            .with_process(&node, deployment.Localhost())
61            .with_external(&external, deployment.Localhost())
62            .deploy(&mut deployment);
63
64        deployment.deploy().await.unwrap();
65
66        let mut external_out = nodes.connect_source_bincode(out_port).await;
67
68        deployment.start().await.unwrap();
69
70        for i in 0..5 {
71            assert_eq!(external_out.next().await.unwrap(), (i, 0));
72        }
73    }
74}