1use std::fmt::{Debug, Formatter};
13use std::marker::PhantomData;
14
15use proc_macro2::Span;
16use quote::quote;
17use stageleft::runtime_support::{FreeVariableWithContextWithProps, QuoteTokens};
18use stageleft::{QuotedWithContextWithProps, quote_type};
19
20use super::dynamic::LocationId;
21use super::{Location, MemberId};
22use crate::compile::builder::FlowState;
23use crate::location::dynamic::ClusterConsistency;
24use crate::location::member_id::TaglessMemberId;
25use crate::location::{LocationKey, TopLevel};
26use crate::staging_util::{Invariant, get_this_crate};
27
28pub trait Consistency {
31 fn consistency() -> ClusterConsistency;
33}
34
35pub enum NoConsistency {}
38impl Consistency for NoConsistency {
39 fn consistency() -> ClusterConsistency {
40 ClusterConsistency::NoConsistency
41 }
42}
43
44pub enum EventualConsistency {}
47impl Consistency for EventualConsistency {
48 fn consistency() -> ClusterConsistency {
49 ClusterConsistency::EventualConsistency
50 }
51}
52
53pub struct Cluster<'a, ClusterTag, Con: Consistency = NoConsistency> {
63 pub(crate) key: LocationKey,
64 pub(crate) flow_state: FlowState,
65 pub(crate) _phantom: Invariant<'a, (ClusterTag, Con)>,
66}
67
68impl<C, Con: Consistency> Debug for Cluster<'_, C, Con> {
69 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
70 write!(f, "Cluster({})", self.key)
71 }
72}
73
74impl<C, Con: Consistency> Eq for Cluster<'_, C, Con> {}
75impl<C, Con: Consistency> PartialEq for Cluster<'_, C, Con> {
76 fn eq(&self, other: &Self) -> bool {
77 self.key == other.key && FlowState::ptr_eq(&self.flow_state, &other.flow_state)
78 }
79}
80
81impl<C, Con: Consistency> Clone for Cluster<'_, C, Con> {
82 fn clone(&self) -> Self {
83 Cluster {
84 key: self.key,
85 flow_state: self.flow_state.clone(),
86 _phantom: PhantomData,
87 }
88 }
89}
90
91impl<'a, C, Con: Consistency> super::dynamic::DynLocation for Cluster<'a, C, Con> {
92 fn dyn_id(&self) -> LocationId {
93 LocationId::Cluster(self.key)
94 }
95
96 fn flow_state(&self) -> &FlowState {
97 &self.flow_state
98 }
99
100 fn is_top_level() -> bool {
101 true
102 }
103
104 fn multiversioned(&self) -> bool {
105 false }
107
108 fn cluster_consistency() -> Option<ClusterConsistency> {
109 Some(Con::consistency())
110 }
111}
112
113impl<'a, C, Con: Consistency> Location<'a> for Cluster<'a, C, Con> {
114 type Root = Cluster<'a, C, Con>;
115
116 type DropConsistency = Cluster<'a, C, NoConsistency>;
117
118 fn consistency() -> Option<ClusterConsistency> {
119 Some(Con::consistency())
120 }
121
122 fn root(&self) -> Self::Root {
123 self.clone()
124 }
125
126 fn drop_consistency(&self) -> Self::DropConsistency {
127 Cluster {
128 key: self.key,
129 flow_state: self.flow_state.clone(),
130 _phantom: PhantomData,
131 }
132 }
133
134 fn from_drop_consistency(l2: Self::DropConsistency) -> Self {
135 Cluster {
136 key: l2.key,
137 flow_state: l2.flow_state,
138 _phantom: PhantomData,
139 }
140 }
141}
142
143impl<'a, C, Con: Consistency> TopLevel<'a> for Cluster<'a, C, Con> {}
144
145#[cfg(feature = "sim")]
146impl<'a, C> Cluster<'a, C> {
147 pub fn sim_input<T>(
152 &self,
153 ) -> (
154 crate::sim::SimClusterSender<
155 T,
156 crate::live_collections::stream::TotalOrder,
157 crate::live_collections::stream::ExactlyOnce,
158 >,
159 crate::live_collections::Stream<
160 T,
161 Self,
162 crate::live_collections::boundedness::Unbounded,
163 crate::live_collections::stream::TotalOrder,
164 crate::live_collections::stream::ExactlyOnce,
165 >,
166 )
167 where
168 T: serde::Serialize + serde::de::DeserializeOwned,
169 {
170 use crate::location::Location;
171
172 let external_location: crate::location::External<'a, ()> = crate::location::External {
173 key: LocationKey::FIRST,
174 flow_state: self.flow_state.clone(),
175 _phantom: PhantomData,
176 };
177
178 let (external, stream) = self.source_external_bincode(&external_location);
179
180 (
181 crate::sim::SimClusterSender(external.port_id, PhantomData),
182 stream,
183 )
184 }
185}
186
187pub struct ClusterIds<'a> {
192 pub key: LocationKey,
194 pub _phantom: PhantomData<&'a ()>,
196}
197
198impl<'a> Clone for ClusterIds<'a> {
199 fn clone(&self) -> Self {
200 Self {
201 key: self.key,
202 _phantom: Default::default(),
203 }
204 }
205}
206
207impl<'a, Ctx> FreeVariableWithContextWithProps<Ctx, ()> for ClusterIds<'a> {
208 type O = &'a [TaglessMemberId];
209
210 fn to_tokens(self, _ctx: &Ctx) -> (QuoteTokens, ())
211 where
212 Self: Sized,
213 {
214 let ident = syn::Ident::new(
215 &format!("__hydro_lang_cluster_ids_{}", self.key),
216 Span::call_site(),
217 );
218
219 (
220 QuoteTokens {
221 prelude: None,
222 expr: Some(quote! { #ident }),
223 },
224 (),
225 )
226 }
227}
228
229impl<'a, Ctx> QuotedWithContextWithProps<'a, &'a [TaglessMemberId], Ctx, ()> for ClusterIds<'a> {}
230
231pub trait IsCluster {
233 type Tag;
235}
236
237impl<C> IsCluster for Cluster<'_, C> {
238 type Tag = C;
239}
240
241pub static CLUSTER_SELF_ID: ClusterSelfId = ClusterSelfId { _private: &() };
244
245#[derive(Clone, Copy)]
250pub struct ClusterSelfId<'a> {
251 _private: &'a (),
252}
253
254impl<'a, L> FreeVariableWithContextWithProps<L, ()> for ClusterSelfId<'a>
255where
256 L: Location<'a>,
257 <L as Location<'a>>::Root: IsCluster,
258{
259 type O = MemberId<<<L as Location<'a>>::Root as IsCluster>::Tag>;
260
261 fn to_tokens(self, ctx: &L) -> (QuoteTokens, ())
262 where
263 Self: Sized,
264 {
265 let LocationId::Cluster(cluster_id) = ctx.root().id() else {
266 unreachable!()
267 };
268
269 let ident = syn::Ident::new(
270 &format!("__hydro_lang_cluster_self_id_{}", cluster_id),
271 Span::call_site(),
272 );
273 let root = get_this_crate();
274 let c_type: syn::Type = quote_type::<<<L as Location<'a>>::Root as IsCluster>::Tag>();
275
276 (
277 QuoteTokens {
278 prelude: None,
279 expr: Some(
280 quote! { #root::__staged::location::MemberId::<#c_type>::from_tagless((#ident).clone()) },
281 ),
282 },
283 (),
284 )
285 }
286}
287
288impl<'a, L>
289 QuotedWithContextWithProps<'a, MemberId<<<L as Location<'a>>::Root as IsCluster>::Tag>, L, ()>
290 for ClusterSelfId<'a>
291where
292 L: Location<'a>,
293 <L as Location<'a>>::Root: IsCluster,
294{
295}
296
297#[cfg(test)]
298mod tests {
299 #[cfg(feature = "sim")]
300 use stageleft::q;
301
302 #[cfg(feature = "sim")]
303 use super::CLUSTER_SELF_ID;
304 #[cfg(feature = "sim")]
305 use crate::location::{Location, MemberId, MembershipEvent};
306 #[cfg(feature = "sim")]
307 use crate::networking::TCP;
308 #[cfg(feature = "sim")]
309 use crate::nondet::nondet;
310 #[cfg(feature = "sim")]
311 use crate::prelude::FlowBuilder;
312
313 #[cfg(feature = "sim")]
314 #[test]
315 fn sim_cluster_self_id() {
316 let mut flow = FlowBuilder::new();
317 let cluster1 = flow.cluster::<()>();
318 let cluster2 = flow.cluster::<()>();
319
320 let node = flow.process::<()>();
321
322 let out_recv = cluster1
323 .source_iter(q!(vec![CLUSTER_SELF_ID]))
324 .send(&node, TCP.fail_stop().bincode())
325 .values()
326 .merge_unordered(
327 cluster2
328 .source_iter(q!(vec![CLUSTER_SELF_ID]))
329 .send(&node, TCP.fail_stop().bincode())
330 .values(),
331 )
332 .sim_output();
333
334 flow.sim()
335 .with_cluster_size(&cluster1, 3)
336 .with_cluster_size(&cluster2, 4)
337 .exhaustive(async || {
338 out_recv
339 .assert_yields_only_unordered([0, 1, 2, 0, 1, 2, 3].map(MemberId::from_raw_id))
340 .await
341 });
342 }
343
344 #[cfg(feature = "sim")]
345 #[test]
346 fn sim_cluster_with_tick() {
347 use std::collections::HashMap;
348
349 let mut flow = FlowBuilder::new();
350 let cluster = flow.cluster::<()>();
351 let node = flow.process::<()>();
352
353 let out_recv = cluster
354 .source_iter(q!(vec![1, 2, 3]))
355 .batch(&cluster.tick(), nondet!())
356 .count()
357 .all_ticks()
358 .send(&node, TCP.fail_stop().bincode())
359 .entries()
360 .map(q!(|(id, v)| (id, v)))
361 .sim_output();
362
363 let count = flow
364 .sim()
365 .with_cluster_size(&cluster, 2)
366 .exhaustive(async || {
367 let grouped = out_recv.collect_sorted::<Vec<_>>().await.into_iter().fold(
368 HashMap::new(),
369 |mut acc: HashMap<MemberId<()>, usize>, (id, v)| {
370 *acc.entry(id).or_default() += v;
371 acc
372 },
373 );
374
375 assert!(grouped.len() == 2);
376 for (_id, v) in grouped {
377 assert!(v == 3);
378 }
379 });
380
381 assert_eq!(count, 106);
382 }
386
387 #[cfg(feature = "sim")]
388 #[test]
389 fn sim_cluster_membership() {
390 let mut flow = FlowBuilder::new();
391 let cluster = flow.cluster::<()>();
392 let node = flow.process::<()>();
393
394 let out_recv = node
395 .source_cluster_membership_stream(&cluster, nondet!())
396 .entries()
397 .map(q!(|(id, v)| (id, v)))
398 .sim_output();
399
400 flow.sim()
401 .with_cluster_size(&cluster, 2)
402 .exhaustive(async || {
403 out_recv
404 .assert_yields_only_unordered(vec![
405 (MemberId::from_raw_id(0), MembershipEvent::Joined),
406 (MemberId::from_raw_id(1), MembershipEvent::Joined),
407 ])
408 .await;
409 });
410 }
411}