1use std::fmt::{Debug, Formatter};
2use std::marker::PhantomData;
3
4use proc_macro2::Span;
5use quote::quote;
6use stageleft::runtime_support::{FreeVariableWithContext, QuoteTokens};
7use stageleft::{QuotedWithContext, quote_type};
8
9use super::dynamic::LocationId;
10use super::{Location, MemberId};
11use crate::compile::builder::FlowState;
12use crate::location::member_id::TaglessMemberId;
13use crate::staging_util::{Invariant, get_this_crate};
14
15pub struct Cluster<'a, ClusterTag> {
16 pub(crate) id: usize,
17 pub(crate) flow_state: FlowState,
18 pub(crate) _phantom: Invariant<'a, ClusterTag>,
19}
20
21impl<C> Debug for Cluster<'_, C> {
22 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
23 write!(f, "Cluster({})", self.id)
24 }
25}
26
27impl<C> Eq for Cluster<'_, C> {}
28impl<C> PartialEq for Cluster<'_, C> {
29 fn eq(&self, other: &Self) -> bool {
30 self.id == other.id && FlowState::ptr_eq(&self.flow_state, &other.flow_state)
31 }
32}
33
34impl<C> Clone for Cluster<'_, C> {
35 fn clone(&self) -> Self {
36 Cluster {
37 id: self.id,
38 flow_state: self.flow_state.clone(),
39 _phantom: PhantomData,
40 }
41 }
42}
43
44impl<'a, C> super::dynamic::DynLocation for Cluster<'a, C> {
45 fn id(&self) -> LocationId {
46 LocationId::Cluster(self.id)
47 }
48
49 fn flow_state(&self) -> &FlowState {
50 &self.flow_state
51 }
52
53 fn is_top_level() -> bool {
54 true
55 }
56}
57
58impl<'a, C> Location<'a> for Cluster<'a, C> {
59 type Root = Cluster<'a, C>;
60
61 fn root(&self) -> Self::Root {
62 self.clone()
63 }
64}
65
66pub struct ClusterIds<'a> {
67 pub id: usize,
68 pub _phantom: PhantomData<&'a ()>,
69}
70
71impl<'a> Clone for ClusterIds<'a> {
72 fn clone(&self) -> Self {
73 Self {
74 id: self.id,
75 _phantom: Default::default(),
76 }
77 }
78}
79
80impl<'a, Ctx> FreeVariableWithContext<Ctx> for ClusterIds<'a> {
81 type O = &'a [TaglessMemberId];
82
83 fn to_tokens(self, _ctx: &Ctx) -> QuoteTokens
84 where
85 Self: Sized,
86 {
87 let ident = syn::Ident::new(
88 &format!("__hydro_lang_cluster_ids_{}", self.id),
89 Span::call_site(),
90 );
91
92 QuoteTokens {
93 prelude: None,
94 expr: Some(quote! { #ident }),
95 }
96 }
97}
98
99impl<'a, Ctx> QuotedWithContext<'a, &'a [TaglessMemberId], Ctx> for ClusterIds<'a> {}
100
101pub trait IsCluster {
102 type Tag;
103}
104
105impl<C> IsCluster for Cluster<'_, C> {
106 type Tag = C;
107}
108
109pub static CLUSTER_SELF_ID: ClusterSelfId = ClusterSelfId { _private: &() };
112
113#[derive(Clone, Copy)]
114pub struct ClusterSelfId<'a> {
115 _private: &'a (),
116}
117
118impl<'a, L> FreeVariableWithContext<L> for ClusterSelfId<'a>
119where
120 L: Location<'a>,
121 <L as Location<'a>>::Root: IsCluster,
122{
123 type O = MemberId<<<L as Location<'a>>::Root as IsCluster>::Tag>;
124
125 fn to_tokens(self, ctx: &L) -> QuoteTokens
126 where
127 Self: Sized,
128 {
129 let cluster_id = if let LocationId::Cluster(id) = ctx.root().id() {
130 id
131 } else {
132 unreachable!()
133 };
134
135 let ident = syn::Ident::new(
136 &format!("__hydro_lang_cluster_self_id_{}", cluster_id),
137 Span::call_site(),
138 );
139 let root = get_this_crate();
140 let c_type: syn::Type = quote_type::<<<L as Location<'a>>::Root as IsCluster>::Tag>();
141
142 QuoteTokens {
143 prelude: None,
144 expr: Some(
145 quote! { #root::location::MemberId::<#c_type>::from_tagless((#ident).clone()) },
146 ),
147 }
148 }
149}
150
151impl<'a, L> QuotedWithContext<'a, MemberId<<<L as Location<'a>>::Root as IsCluster>::Tag>, L>
152 for ClusterSelfId<'a>
153where
154 L: Location<'a>,
155 <L as Location<'a>>::Root: IsCluster,
156{
157}
158
159#[cfg(test)]
160mod tests {
161 #[cfg(feature = "sim")]
162 use stageleft::q;
163
164 #[cfg(feature = "sim")]
165 use super::CLUSTER_SELF_ID;
166 #[cfg(feature = "sim")]
167 use crate::location::{Location, MemberId, MembershipEvent};
168 #[cfg(feature = "sim")]
169 use crate::networking::TCP;
170 #[cfg(feature = "sim")]
171 use crate::nondet::nondet;
172 #[cfg(feature = "sim")]
173 use crate::prelude::FlowBuilder;
174
175 #[cfg(feature = "sim")]
176 #[test]
177 fn sim_cluster_self_id() {
178 let flow = FlowBuilder::new();
179 let cluster1 = flow.cluster::<()>();
180 let cluster2 = flow.cluster::<()>();
181
182 let node = flow.process::<()>();
183
184 let out_recv = cluster1
185 .source_iter(q!(vec![CLUSTER_SELF_ID]))
186 .send(&node, TCP.bincode())
187 .values()
188 .interleave(
189 cluster2
190 .source_iter(q!(vec![CLUSTER_SELF_ID]))
191 .send(&node, TCP.bincode())
192 .values(),
193 )
194 .sim_output();
195
196 flow.sim()
197 .with_cluster_size(&cluster1, 3)
198 .with_cluster_size(&cluster2, 4)
199 .exhaustive(async || {
200 out_recv
201 .assert_yields_only_unordered([0, 1, 2, 0, 1, 2, 3].map(MemberId::from_raw_id))
202 .await
203 });
204 }
205
206 #[cfg(feature = "sim")]
207 #[test]
208 fn sim_cluster_with_tick() {
209 use std::collections::HashMap;
210
211 let flow = FlowBuilder::new();
212 let cluster = flow.cluster::<()>();
213 let node = flow.process::<()>();
214
215 let out_recv = cluster
216 .source_iter(q!(vec![1, 2, 3]))
217 .batch(&cluster.tick(), nondet!())
218 .count()
219 .all_ticks()
220 .send(&node, TCP.bincode())
221 .entries()
222 .map(q!(|(id, v)| (id, v)))
223 .sim_output();
224
225 let count = flow
226 .sim()
227 .with_cluster_size(&cluster, 2)
228 .exhaustive(async || {
229 let grouped = out_recv.collect_sorted::<Vec<_>>().await.into_iter().fold(
230 HashMap::new(),
231 |mut acc: HashMap<MemberId<()>, usize>, (id, v)| {
232 *acc.entry(id).or_default() += v;
233 acc
234 },
235 );
236
237 assert!(grouped.len() == 2);
238 for (_id, v) in grouped {
239 assert!(v == 3);
240 }
241 });
242
243 assert_eq!(count, 106);
244 }
248
249 #[cfg(feature = "sim")]
250 #[test]
251 fn sim_cluster_membership() {
252 let flow = FlowBuilder::new();
253 let cluster = flow.cluster::<()>();
254 let node = flow.process::<()>();
255
256 let out_recv = node
257 .source_cluster_members(&cluster)
258 .entries()
259 .map(q!(|(id, v)| (id, v)))
260 .sim_output();
261
262 flow.sim()
263 .with_cluster_size(&cluster, 2)
264 .exhaustive(async || {
265 out_recv
266 .assert_yields_only_unordered(vec![
267 (MemberId::from_raw_id(0), MembershipEvent::Joined),
268 (MemberId::from_raw_id(1), MembershipEvent::Joined),
269 ])
270 .await;
271 });
272 }
273}