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::{LocationKey, TopLevel};
25use crate::staging_util::{Invariant, get_this_crate};
26
27pub trait Consistency {
30 fn consistency() -> ClusterConsistency;
32}
33
34pub enum NoConsistency {}
37impl Consistency for NoConsistency {
38 fn consistency() -> ClusterConsistency {
39 ClusterConsistency::NoConsistency
40 }
41}
42
43pub enum EventualConsistency {}
46impl Consistency for EventualConsistency {
47 fn consistency() -> ClusterConsistency {
48 ClusterConsistency::EventualConsistency
49 }
50}
51
52pub struct Cluster<'a, ClusterTag, Id = u32, Con: Consistency = NoConsistency> {
62 pub(crate) key: LocationKey,
63 pub(crate) flow_state: FlowState,
64 pub(crate) _phantom: Invariant<'a, (ClusterTag, Con, Id)>,
65}
66
67impl<C, Con: Consistency, Id> Debug for Cluster<'_, C, Id, Con> {
68 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
69 write!(f, "Cluster({})", self.key)
70 }
71}
72
73impl<C, Con: Consistency, Id> Eq for Cluster<'_, C, Id, Con> {}
74impl<C, Con: Consistency, Id> PartialEq for Cluster<'_, C, Id, Con> {
75 fn eq(&self, other: &Self) -> bool {
76 self.key == other.key && FlowState::ptr_eq(&self.flow_state, &other.flow_state)
77 }
78}
79
80impl<C, Con: Consistency, Id> Clone for Cluster<'_, C, Id, Con> {
81 fn clone(&self) -> Self {
82 Cluster {
83 key: self.key,
84 flow_state: self.flow_state.clone(),
85 _phantom: PhantomData,
86 }
87 }
88}
89
90impl<'a, C, Con: Consistency, Id> super::dynamic::DynLocation for Cluster<'a, C, Id, Con> {
91 fn dyn_id(&self) -> LocationId {
92 LocationId::Cluster(self.key)
93 }
94
95 fn flow_state(&self) -> &FlowState {
96 &self.flow_state
97 }
98
99 fn is_top_level() -> bool {
100 true
101 }
102
103 fn multiversioned(&self) -> bool {
104 false }
106
107 fn cluster_consistency() -> Option<ClusterConsistency> {
108 Some(Con::consistency())
109 }
110}
111
112impl<'a, C, Con: Consistency, Id> Location<'a> for Cluster<'a, C, Id, Con> {
113 type Root = Cluster<'a, C, Id, Con>;
114
115 type SimHookScope = crate::sim_hooks::OnCluster<C>;
116
117 type DropConsistency = Cluster<'a, C, Id>;
118
119 fn consistency() -> Option<ClusterConsistency> {
120 Some(Con::consistency())
121 }
122
123 fn root(&self) -> Self::Root {
124 self.clone()
125 }
126
127 fn drop_consistency(&self) -> Self::DropConsistency {
128 Cluster {
129 key: self.key,
130 flow_state: self.flow_state.clone(),
131 _phantom: PhantomData,
132 }
133 }
134
135 fn from_drop_consistency(l2: Self::DropConsistency) -> Self {
136 Cluster {
137 key: l2.key,
138 flow_state: l2.flow_state,
139 _phantom: PhantomData,
140 }
141 }
142}
143
144impl<'a, C, Con: Consistency, Id> TopLevel<'a> for Cluster<'a, C, Id, Con> {}
145
146#[cfg(feature = "sim")]
147impl<'a, C> Cluster<'a, C> {
148 pub fn sim_input<
161 T,
162 O: crate::live_collections::stream::Ordering,
163 R: crate::live_collections::stream::Retries,
164 >(
165 &self,
166 ) -> (
167 crate::sim::SimClusterSender<T, O, R>,
168 crate::live_collections::Stream<
169 T,
170 Self,
171 crate::live_collections::boundedness::Unbounded,
172 O,
173 R,
174 >,
175 )
176 where
177 T: serde::Serialize + serde::de::DeserializeOwned,
178 {
179 self.sim_input_with::<crate::sim::codec::RmpCodec, T, O, R>()
180 }
181
182 pub fn sim_input_with<
191 Codec: crate::sim::codec::SimCodec<T>,
192 T,
193 O: crate::live_collections::stream::Ordering,
194 R: crate::live_collections::stream::Retries,
195 >(
196 &self,
197 ) -> (
198 crate::sim::SimClusterSender<T, O, R>,
199 crate::live_collections::Stream<
200 T,
201 Self,
202 crate::live_collections::boundedness::Unbounded,
203 O,
204 R,
205 >,
206 ) {
207 let external_location: crate::location::External<'a, ()> = crate::location::External {
208 key: LocationKey::FIRST,
209 flow_state: self.flow_state.clone(),
210 _phantom: PhantomData,
211 };
212
213 let (external_port_id, stream) = super::register_serialized_external_input(
214 self,
215 &external_location,
216 crate::sim::codec::staged_deserialize::<T, Codec>(),
217 );
218
219 (
220 crate::sim::SimClusterSender(external_port_id, PhantomData, Codec::encode),
221 stream.weaken_ordering().weaken_retries(),
222 )
223 }
224}
225
226pub struct ClusterIds<'a, Id> {
230 pub key: LocationKey,
232 pub _phantom: PhantomData<&'a Id>,
234}
235
236impl<'a, Id> Clone for ClusterIds<'a, Id> {
237 fn clone(&self) -> Self {
238 Self {
239 key: self.key,
240 _phantom: Default::default(),
241 }
242 }
243}
244
245impl<'a, Ctx, Id: 'a> FreeVariableWithContextWithProps<Ctx, ()> for ClusterIds<'a, Id> {
246 type O = &'a [Id];
247
248 fn to_tokens(self, _ctx: &Ctx) -> (QuoteTokens, ())
249 where
250 Self: Sized,
251 {
252 let ident = syn::Ident::new(
253 &format!("__hydro_lang_cluster_ids_{}", self.key),
254 Span::call_site(),
255 );
256
257 (
258 QuoteTokens {
259 prelude: None,
260 expr: Some(quote! { #ident }),
261 },
262 (),
263 )
264 }
265}
266
267impl<'a, Ctx, Id: 'a> QuotedWithContextWithProps<'a, &'a [Id], Ctx, ()> for ClusterIds<'a, Id> {}
268
269pub trait IsCluster {
271 type Tag;
273 type Id;
275}
276
277impl<C, Id> IsCluster for Cluster<'_, C, Id> {
278 type Tag = C;
279 type Id = Id;
280}
281
282pub static CLUSTER_SELF_ID: ClusterSelfId<'static> = ClusterSelfId { _private: &() };
285
286#[derive(Clone, Copy)]
291pub struct ClusterSelfId<'a> {
292 _private: &'a (),
293}
294
295impl<'a, Ctx> FreeVariableWithContextWithProps<Ctx, ()> for ClusterSelfId<'a>
296where
297 Ctx: crate::live_collections::ContextWithLocation<'a>,
298 <Ctx::Location as Location<'a>>::Root: IsCluster,
299{
300 type O = MemberId<
301 <<Ctx::Location as Location<'a>>::Root as IsCluster>::Tag,
302 <<Ctx::Location as Location<'a>>::Root as IsCluster>::Id,
303 >;
304
305 fn to_tokens(self, ctx: &Ctx) -> (QuoteTokens, ())
306 where
307 Self: Sized,
308 {
309 let LocationId::Cluster(cluster_id) = ctx.context_location().root().id() else {
310 unreachable!()
311 };
312 crate::location::dynamic::DynLocation::flow_state(ctx.context_location())
313 .borrow_mut()
314 .clusters_reading_self_id
315 .insert(cluster_id);
316
317 let ident = syn::Ident::new(
318 &format!("__hydro_lang_cluster_self_id_{}", cluster_id),
319 Span::call_site(),
320 );
321 let root = get_this_crate();
322 let c_type: syn::Type =
323 quote_type::<<<Ctx::Location as Location<'a>>::Root as IsCluster>::Tag>();
324
325 (
326 QuoteTokens {
327 prelude: None,
328 expr: Some(
329 quote! { #root::__staged::location::MemberId::<#c_type, _>::from_tagless((#ident).clone()) },
330 ),
331 },
332 (),
333 )
334 }
335}
336
337impl<'a, Ctx>
338 QuotedWithContextWithProps<
339 'a,
340 MemberId<
341 <<Ctx::Location as Location<'a>>::Root as IsCluster>::Tag,
342 <<Ctx::Location as Location<'a>>::Root as IsCluster>::Id,
343 >,
344 Ctx,
345 (),
346 > for ClusterSelfId<'a>
347where
348 Ctx: crate::live_collections::ContextWithLocation<'a>,
349 <Ctx::Location as Location<'a>>::Root: IsCluster,
350{
351}
352
353#[cfg(test)]
354mod tests {
355 #[cfg(feature = "sim")]
356 use stageleft::q;
357
358 #[cfg(feature = "sim")]
359 use super::CLUSTER_SELF_ID;
360 #[cfg(feature = "sim")]
361 use crate::location::{Location, MemberId, MembershipEvent};
362 #[cfg(feature = "sim")]
363 use crate::networking::TCP;
364 #[cfg(feature = "sim")]
365 use crate::nondet::nondet;
366 #[cfg(feature = "sim")]
367 use crate::prelude::FlowBuilder;
368
369 #[cfg(feature = "sim")]
370 #[test]
371 fn sim_cluster_self_id() {
372 let mut flow = FlowBuilder::new();
373 let cluster1 = flow.cluster::<(), u32>();
374 let cluster2 = flow.cluster::<(), u32>();
375
376 let node = flow.process::<()>();
377
378 let out_recv = cluster1
379 .source_iter(q!(vec![CLUSTER_SELF_ID]))
380 .send(&node, TCP.fail_stop().bincode())
381 .values()
382 .merge_unordered(
383 cluster2
384 .source_iter(q!(vec![CLUSTER_SELF_ID]))
385 .send(&node, TCP.fail_stop().bincode())
386 .values(),
387 )
388 .sim_output();
389
390 flow.sim()
391 .with_cluster_size(&cluster1, 3)
392 .with_cluster_size(&cluster2, 4)
393 .exhaustive(async || {
394 out_recv
395 .assert_yields_only_unordered([0, 1, 2, 0, 1, 2, 3].map(MemberId::from_raw_id))
396 .await
397 });
398 }
399
400 #[cfg(feature = "sim")]
401 #[test]
402 fn sim_cluster_with_tick() {
403 use std::collections::HashMap;
404
405 let mut flow = FlowBuilder::new();
406 let cluster = flow.cluster::<(), u32>();
407 let node = flow.process::<()>();
408
409 let out_recv = cluster
410 .source_iter(q!(vec![1, 2, 3]))
411 .batch(&cluster.tick(), nondet!())
412 .count()
413 .all_ticks()
414 .send(&node, TCP.fail_stop().bincode())
415 .entries()
416 .map(q!(|(id, v)| (id, v)))
417 .sim_output();
418
419 let count = flow
420 .sim()
421 .with_cluster_size(&cluster, 2)
422 .exhaustive(async || {
423 let grouped = out_recv.collect_sorted::<Vec<_>>().await.into_iter().fold(
424 HashMap::new(),
425 |mut acc: HashMap<MemberId<()>, usize>, (id, v)| {
426 *acc.entry(id).or_default() += v;
427 acc
428 },
429 );
430
431 assert_eq!(grouped.len(), 2);
432 for (_id, v) in grouped {
433 assert_eq!(v, 3);
434 }
435 });
436
437 assert_eq!(count, 106);
438 }
442
443 #[cfg(feature = "sim")]
444 #[test]
445 fn sim_cluster_membership() {
446 let mut flow = FlowBuilder::new();
447 let cluster = flow.cluster::<(), u32>();
448 let node = flow.process::<()>();
449
450 let out_recv = node
451 .source_cluster_membership_stream(&cluster, nondet!())
452 .entries()
453 .map(q!(|(id, v)| (id, v)))
454 .sim_output();
455
456 flow.sim()
457 .with_cluster_size(&cluster, 2)
458 .exhaustive(async || {
459 out_recv
460 .assert_yields_only_unordered(vec![
461 (MemberId::from_raw_id(0), MembershipEvent::Joined),
462 (MemberId::from_raw_id(1), MembershipEvent::Joined),
463 ])
464 .await;
465 });
466 }
467}