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::nondet::nondet;
170 #[cfg(feature = "sim")]
171 use crate::prelude::FlowBuilder;
172
173 #[cfg(feature = "sim")]
174 #[test]
175 fn sim_cluster_self_id() {
176 let flow = FlowBuilder::new();
177 let cluster1 = flow.cluster::<()>();
178 let cluster2 = flow.cluster::<()>();
179
180 let node = flow.process::<()>();
181
182 let out_recv = cluster1
183 .source_iter(q!(vec![CLUSTER_SELF_ID]))
184 .send_bincode(&node)
185 .values()
186 .interleave(
187 cluster2
188 .source_iter(q!(vec![CLUSTER_SELF_ID]))
189 .send_bincode(&node)
190 .values(),
191 )
192 .sim_output();
193
194 flow.sim()
195 .with_cluster_size(&cluster1, 3)
196 .with_cluster_size(&cluster2, 4)
197 .exhaustive(async || {
198 out_recv
199 .assert_yields_only_unordered([0, 1, 2, 0, 1, 2, 3].map(MemberId::from_raw_id))
200 .await
201 });
202 }
203
204 #[cfg(feature = "sim")]
205 #[test]
206 fn sim_cluster_with_tick() {
207 use std::collections::HashMap;
208
209 let flow = FlowBuilder::new();
210 let cluster = flow.cluster::<()>();
211 let node = flow.process::<()>();
212
213 let out_recv = cluster
214 .source_iter(q!(vec![1, 2, 3]))
215 .batch(&cluster.tick(), nondet!())
216 .count()
217 .all_ticks()
218 .send_bincode(&node)
219 .entries()
220 .map(q!(|(id, v)| (id, v)))
221 .sim_output();
222
223 let count = flow
224 .sim()
225 .with_cluster_size(&cluster, 2)
226 .exhaustive(async || {
227 let grouped = out_recv.collect_sorted::<Vec<_>>().await.into_iter().fold(
228 HashMap::new(),
229 |mut acc: HashMap<MemberId<()>, usize>, (id, v)| {
230 *acc.entry(id).or_default() += v;
231 acc
232 },
233 );
234
235 assert!(grouped.len() == 2);
236 for (_id, v) in grouped {
237 assert!(v == 3);
238 }
239 });
240
241 assert_eq!(count, 106);
242 }
246
247 #[cfg(feature = "sim")]
248 #[test]
249 fn sim_cluster_membership() {
250 let flow = FlowBuilder::new();
251 let cluster = flow.cluster::<()>();
252 let node = flow.process::<()>();
253
254 let out_recv = node
255 .source_cluster_members(&cluster)
256 .entries()
257 .map(q!(|(id, v)| (id, v)))
258 .sim_output();
259
260 flow.sim()
261 .with_cluster_size(&cluster, 2)
262 .exhaustive(async || {
263 out_recv
264 .assert_yields_only_unordered(vec![
265 (MemberId::from_raw_id(0), MembershipEvent::Joined),
266 (MemberId::from_raw_id(1), MembershipEvent::Joined),
267 ])
268 .await;
269 });
270 }
271}