1use crate::config::ComponentConfig;
5use crate::context::CuContext;
6use crate::reflect::{GetTypeRegistration, Reflect, TypePath, TypeRegistry};
7#[cfg(feature = "reflect")]
8use bevy_reflect;
9use bincode::de::{Decode, Decoder};
10use bincode::enc::{Encode, Encoder};
11use bincode::error::{DecodeError, EncodeError};
12use compact_str::{CompactString, ToCompactString};
13use core::any::{TypeId, type_name};
14use cu29_clock::{PartialCuTimeRange, Tov};
15use cu29_traits::{
16 COMPACT_STRING_CAPACITY, CuCompactString, CuError, CuMsgMetadataTrait, CuMsgOrigin, CuResult,
17 ErasedCuStampedData, Metadata,
18};
19use serde::de::DeserializeOwned;
20use serde::{Deserialize, Serialize};
21
22use alloc::format;
23use core::fmt::{Debug, Display, Formatter, Result as FmtResult};
24
25#[cfg(feature = "reflect")]
28pub trait CuMsgPayload:
29 Default
30 + Debug
31 + Clone
32 + Encode
33 + Decode<()>
34 + Serialize
35 + DeserializeOwned
36 + Reflect
37 + TypePath
38 + GetTypeRegistration
39 + Sized
40{
41}
42
43#[cfg(not(feature = "reflect"))]
44pub trait CuMsgPayload:
45 Default + Debug + Clone + Encode + Decode<()> + Serialize + DeserializeOwned + Reflect + Sized
46{
47}
48
49pub trait CuMsgPack {}
50
51#[cfg(feature = "reflect")]
53impl<T> CuMsgPayload for T where
54 T: Default
55 + Debug
56 + Clone
57 + Encode
58 + Decode<()>
59 + Serialize
60 + DeserializeOwned
61 + Reflect
62 + TypePath
63 + GetTypeRegistration
64 + Sized
65{
66}
67
68#[cfg(not(feature = "reflect"))]
69impl<T> CuMsgPayload for T where
70 T: Default
71 + Debug
72 + Clone
73 + Encode
74 + Decode<()>
75 + Serialize
76 + DeserializeOwned
77 + Reflect
78 + Sized
79{
80}
81
82macro_rules! impl_cu_msg_pack {
83 ($($name:ident),+) => {
84 impl<'cl, $($name),+> CuMsgPack for ($(&CuMsg<$name>,)+)
85 where
86 $($name: CuMsgPayload),+
87 {}
88 };
89}
90
91macro_rules! impl_cu_msg_pack_up_to {
92 ($first:ident, $second:ident $(, $rest:ident)* $(,)?) => {
93 impl_cu_msg_pack!($first, $second);
94 impl_cu_msg_pack_up_to!(@accumulate ($first, $second); $($rest),*);
95 };
96 (@accumulate ($($acc:ident),+);) => {};
97 (@accumulate ($($acc:ident),+); $next:ident $(, $rest:ident)*) => {
98 impl_cu_msg_pack!($($acc),+, $next);
99 impl_cu_msg_pack_up_to!(@accumulate ($($acc),+, $next); $($rest),*);
100 };
101}
102
103impl<T: CuMsgPayload> CuMsgPack for CuMsg<T> {}
104impl<T: CuMsgPayload> CuMsgPack for &CuMsg<T> {}
105impl<T: CuMsgPayload> CuMsgPack for (&CuMsg<T>,) {}
106impl CuMsgPack for () {}
107
108impl_cu_msg_pack_up_to!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
110
111#[macro_export]
114macro_rules! input_msg {
115 ($lt:lifetime, $first:ty, $($rest:ty),+) => {
116 ( & $lt CuMsg<$first>, $( & $lt CuMsg<$rest> ),+ )
117 };
118 ($ty:ty) => {
119 CuMsg<$ty>
120 };
121}
122
123#[macro_export]
125macro_rules! output_msg {
126 ($lt:lifetime, $first:ty, $($rest:ty),+) => {
127 ( CuMsg<$first>, $( CuMsg<$rest> ),+ )
128 };
129 ($first:ty, $($rest:ty),+) => {
130 ( CuMsg<$first>, $( CuMsg<$rest> ),+ )
131 };
132 ($ty:ty) => {
133 CuMsg<$ty>
134 };
135}
136
137pub trait CuSingleOutputMsg {
140 type Payload: CuMsgPayload;
141}
142
143impl<T: CuMsgPayload> CuSingleOutputMsg for CuMsg<T> {
144 type Payload = T;
145}
146
147#[derive(Debug, Clone, bincode::Encode, bincode::Decode, Serialize, Deserialize, Reflect)]
149#[reflect(opaque, from_reflect = false, no_field_bounds)]
150pub struct CuMsgMetadata {
151 pub process_time: PartialCuTimeRange,
153 pub status_txt: CuCompactString,
156 pub origin: Option<CuMsgOrigin>,
158}
159
160impl Metadata for CuMsgMetadata {}
161
162impl CuMsgMetadata {
163 pub fn set_status(&mut self, status: impl ToCompactString) {
164 self.status_txt = CuCompactString(status.to_compact_string());
165 }
166
167 pub fn set_origin(&mut self, origin: CuMsgOrigin) {
168 self.origin = Some(origin);
169 }
170
171 pub fn clear_origin(&mut self) {
172 self.origin = None;
173 }
174}
175
176impl CuMsgMetadataTrait for CuMsgMetadata {
177 fn process_time(&self) -> PartialCuTimeRange {
178 self.process_time
179 }
180
181 fn status_txt(&self) -> &CuCompactString {
182 &self.status_txt
183 }
184
185 fn origin(&self) -> Option<&CuMsgOrigin> {
186 self.origin.as_ref()
187 }
188}
189
190impl Display for CuMsgMetadata {
191 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
192 write!(
193 f,
194 "process_time start: {}, process_time end: {}",
195 self.process_time.start, self.process_time.end
196 )
197 }
198}
199
200#[derive(Default, Debug, Clone, bincode::Decode, Serialize, Deserialize, Reflect)]
202#[reflect(opaque, from_reflect = false, no_field_bounds)]
203#[serde(bound(
204 serialize = "T: Serialize, M: Serialize",
205 deserialize = "T: DeserializeOwned, M: DeserializeOwned"
206))]
207pub struct CuStampedData<T, M>
208where
209 T: CuMsgPayload,
210 M: Metadata,
211{
212 payload: Option<T>,
214
215 pub tov: Tov,
218
219 pub metadata: M,
221}
222
223impl<T, M> Encode for CuStampedData<T, M>
224where
225 T: CuMsgPayload,
226 M: Metadata,
227{
228 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
229 match &self.payload {
237 None => {
238 0u8.encode(encoder)?;
239 }
240 Some(payload) => {
241 1u8.encode(encoder)?;
242 let encoded_start = cu29_traits::observed_encode_bytes();
243 let handle_start = crate::monitoring::current_payload_handle_bytes();
244 payload.encode(encoder)?;
245 let encoded_bytes =
246 cu29_traits::observed_encode_bytes().saturating_sub(encoded_start);
247 let handle_bytes =
248 crate::monitoring::current_payload_handle_bytes().saturating_sub(handle_start);
249 crate::monitoring::record_current_slot_payload_io_stats(
250 core::mem::size_of::<T>(),
251 encoded_bytes,
252 handle_bytes,
253 );
254 }
255 }
256 self.tov.encode(encoder)?;
257 self.metadata.encode(encoder)?;
258 Ok(())
259 }
260}
261
262pub fn encode_metadata_only<T, M, E>(
270 msg: &CuStampedData<T, M>,
271 encoder: &mut E,
272) -> Result<(), EncodeError>
273where
274 T: CuMsgPayload,
275 M: Metadata,
276 E: Encoder,
277{
278 0u8.encode(encoder)?;
279 msg.tov.encode(encoder)?;
280 msg.metadata.encode(encoder)?;
281 Ok(())
282}
283
284impl Default for CuMsgMetadata {
285 fn default() -> Self {
286 CuMsgMetadata {
287 process_time: PartialCuTimeRange::default(),
288 status_txt: CuCompactString(CompactString::with_capacity(COMPACT_STRING_CAPACITY)),
289 origin: None,
290 }
291 }
292}
293
294impl<T, M> CuStampedData<T, M>
295where
296 T: CuMsgPayload,
297 M: Metadata,
298{
299 pub(crate) fn from_parts(payload: Option<T>, tov: Tov, metadata: M) -> Self {
300 CuStampedData {
301 payload,
302 tov,
303 metadata,
304 }
305 }
306
307 pub fn new(payload: Option<T>) -> Self {
308 Self::from_parts(payload, Tov::default(), M::default())
309 }
310 pub fn payload(&self) -> Option<&T> {
311 self.payload.as_ref()
312 }
313
314 pub fn set_payload(&mut self, payload: T) {
315 self.payload = Some(payload);
316 }
317
318 pub fn clear_payload(&mut self) {
319 self.payload = None;
320 }
321
322 pub fn payload_mut(&mut self) -> &mut Option<T> {
323 &mut self.payload
324 }
325}
326
327impl<T, M> ErasedCuStampedData for CuStampedData<T, M>
328where
329 T: CuMsgPayload,
330 M: CuMsgMetadataTrait + Metadata,
331{
332 fn payload(&self) -> Option<&dyn erased_serde::Serialize> {
333 self.payload
334 .as_ref()
335 .map(|p| p as &dyn erased_serde::Serialize)
336 }
337
338 #[cfg(feature = "reflect")]
339 fn payload_reflect(&self) -> Option<&dyn cu29_traits::Reflect> {
340 self.payload
341 .as_ref()
342 .map(|p| p as &dyn cu29_traits::Reflect)
343 }
344
345 fn tov(&self) -> Tov {
346 self.tov
347 }
348
349 fn metadata(&self) -> &dyn CuMsgMetadataTrait {
350 &self.metadata
351 }
352}
353
354pub type CuMsg<T> = CuStampedData<T, CuMsgMetadata>;
357
358impl<T: CuMsgPayload> CuStampedData<T, CuMsgMetadata> {
359 pub unsafe fn assume_payload<U: CuMsgPayload>(&self) -> &CuMsg<U> {
366 unsafe { &*(self as *const CuMsg<T> as *const CuMsg<U>) }
368 }
369
370 pub unsafe fn assume_payload_mut<U: CuMsgPayload>(&mut self) -> &mut CuMsg<U> {
377 unsafe { &mut *(self as *mut CuMsg<T> as *mut CuMsg<U>) }
379 }
380}
381
382impl<T: CuMsgPayload + 'static> CuStampedData<T, CuMsgMetadata> {
383 fn downcast_err<U: CuMsgPayload + 'static>() -> CuError {
384 CuError::from(format!(
385 "CuMsg payload mismatch: {} cannot be reinterpreted as {}",
386 type_name::<T>(),
387 type_name::<U>()
388 ))
389 }
390
391 pub fn downcast_ref<U: CuMsgPayload + 'static>(&self) -> CuResult<&CuMsg<U>> {
393 if TypeId::of::<T>() == TypeId::of::<U>() {
394 Ok(unsafe { self.assume_payload::<U>() })
396 } else {
397 Err(Self::downcast_err::<U>())
398 }
399 }
400
401 pub fn downcast_mut<U: CuMsgPayload + 'static>(&mut self) -> CuResult<&mut CuMsg<U>> {
403 if TypeId::of::<T>() == TypeId::of::<U>() {
404 Ok(unsafe { self.assume_payload_mut::<U>() })
406 } else {
407 Err(Self::downcast_err::<U>())
408 }
409 }
410}
411
412pub trait Freezable {
415 fn freeze<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
419 Encode::encode(&(), encoder) }
421
422 fn thaw<D: Decoder>(&mut self, _decoder: &mut D) -> Result<(), DecodeError> {
425 Ok(())
426 }
427}
428
429pub struct BincodeAdapter<'a, T: Freezable + ?Sized>(pub &'a T);
432
433impl<'a, T: Freezable + ?Sized> Encode for BincodeAdapter<'a, T> {
434 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
435 self.0.freeze(encoder)
436 }
437}
438
439pub trait CuSrcTask: Freezable + Reflect {
444 type Output<'m>: CuMsgPayload;
445 type Resources<'r>;
447
448 fn register_debug_state_types(registry: &mut TypeRegistry)
454 where
455 Self: GetTypeRegistration + Sized,
456 {
457 registry.register::<Self>();
458 }
459
460 fn debug_state_type_path() -> &'static str
462 where
463 Self: TypePath + Sized,
464 {
465 Self::type_path()
466 }
467
468 fn with_debug_state<R>(&self, f: impl FnOnce(&dyn Reflect) -> R) -> R
473 where
474 Self: Sized,
475 {
476 f(self)
477 }
478
479 fn new(_config: Option<&ComponentConfig>, _resources: Self::Resources<'_>) -> CuResult<Self>
482 where
483 Self: Sized;
484
485 fn start(&mut self, _ctx: &CuContext) -> CuResult<()> {
487 Ok(())
488 }
489
490 fn preprocess(&mut self, _ctx: &CuContext) -> CuResult<()> {
494 Ok(())
495 }
496
497 fn process<'o>(&mut self, ctx: &CuContext, new_msg: &mut Self::Output<'o>) -> CuResult<()>;
501
502 fn postprocess(&mut self, _ctx: &CuContext) -> CuResult<()> {
506 Ok(())
507 }
508
509 fn stop(&mut self, _ctx: &CuContext) -> CuResult<()> {
511 Ok(())
512 }
513}
514
515pub trait CuTask: Freezable + Reflect {
517 type Input<'m>: CuMsgPack;
518 type Output<'m>: CuMsgPayload;
519 type Resources<'r>;
521
522 fn register_debug_state_types(registry: &mut TypeRegistry)
528 where
529 Self: GetTypeRegistration + Sized,
530 {
531 registry.register::<Self>();
532 }
533
534 fn debug_state_type_path() -> &'static str
536 where
537 Self: TypePath + Sized,
538 {
539 Self::type_path()
540 }
541
542 fn with_debug_state<R>(&self, f: impl FnOnce(&dyn Reflect) -> R) -> R
547 where
548 Self: Sized,
549 {
550 f(self)
551 }
552
553 fn new(_config: Option<&ComponentConfig>, _resources: Self::Resources<'_>) -> CuResult<Self>
556 where
557 Self: Sized;
558
559 fn start(&mut self, _ctx: &CuContext) -> CuResult<()> {
561 Ok(())
562 }
563
564 fn preprocess(&mut self, _ctx: &CuContext) -> CuResult<()> {
568 Ok(())
569 }
570
571 fn process<'i, 'o>(
575 &mut self,
576 _ctx: &CuContext,
577 input: &Self::Input<'i>,
578 output: &mut Self::Output<'o>,
579 ) -> CuResult<()>;
580
581 fn postprocess(&mut self, _ctx: &CuContext) -> CuResult<()> {
585 Ok(())
586 }
587
588 fn stop(&mut self, _ctx: &CuContext) -> CuResult<()> {
590 Ok(())
591 }
592}
593
594pub trait CuSinkTask: Freezable + Reflect {
596 type Input<'m>: CuMsgPack;
597 type Resources<'r>;
599
600 fn register_debug_state_types(registry: &mut TypeRegistry)
606 where
607 Self: GetTypeRegistration + Sized,
608 {
609 registry.register::<Self>();
610 }
611
612 fn debug_state_type_path() -> &'static str
614 where
615 Self: TypePath + Sized,
616 {
617 Self::type_path()
618 }
619
620 fn with_debug_state<R>(&self, f: impl FnOnce(&dyn Reflect) -> R) -> R
625 where
626 Self: Sized,
627 {
628 f(self)
629 }
630
631 fn new(_config: Option<&ComponentConfig>, _resources: Self::Resources<'_>) -> CuResult<Self>
634 where
635 Self: Sized;
636
637 fn start(&mut self, _ctx: &CuContext) -> CuResult<()> {
639 Ok(())
640 }
641
642 fn preprocess(&mut self, _ctx: &CuContext) -> CuResult<()> {
646 Ok(())
647 }
648
649 fn process<'i>(&mut self, _ctx: &CuContext, input: &Self::Input<'i>) -> CuResult<()>;
653
654 fn postprocess(&mut self, _ctx: &CuContext) -> CuResult<()> {
658 Ok(())
659 }
660
661 fn stop(&mut self, _ctx: &CuContext) -> CuResult<()> {
663 Ok(())
664 }
665}
666
667#[cfg(test)]
668mod tests {
669 use super::*;
670 use bincode::{config, decode_from_slice, encode_to_vec};
671
672 #[test]
673 fn test_cucompactstr_encode_decode() {
674 let cstr = CuCompactString(CompactString::from("hello"));
675 let config = config::standard();
676 let encoded = encode_to_vec(&cstr, config).expect("Encoding failed");
677 let (decoded, _): (CuCompactString, usize) =
678 decode_from_slice(&encoded, config).expect("Decoding failed");
679 assert_eq!(cstr.0, decoded.0);
680 }
681
682 #[cfg(not(feature = "reflect"))]
690 #[derive(Debug, Clone, bincode::Encode, bincode::Decode, Serialize, Deserialize)]
691 struct TestHandlePayload {
692 handle: crate::pool::CuHandle<Vec<u8>>,
693 }
694
695 #[cfg(not(feature = "reflect"))]
696 impl Default for TestHandlePayload {
697 fn default() -> Self {
698 Self {
699 handle: crate::pool::CuHandle::new_detached(Vec::new()),
700 }
701 }
702 }
703
704 #[cfg(not(feature = "reflect"))]
705 impl TestHandlePayload {
706 fn payload_should_log(&self) -> bool {
709 self.handle.payload_should_log()
710 }
711 }
712
713 #[cfg(not(feature = "reflect"))]
719 #[test]
720 fn test_encode_skips_payload_for_untouched_handle() {
721 use crate::pool::{CuHandle, HandleContent};
722 let cfg = config::standard();
723
724 let untouched = TestHandlePayload {
725 handle: CuHandle::new_detached_with_mode(
726 vec![0xAA, 0xBB, 0xCC, 0xDD],
727 HandleContent::TouchedOnly,
728 ),
729 };
730 let msg_skip: CuMsg<TestHandlePayload> = CuMsg::new(Some(untouched));
731 let skip_bytes = encode_to_vec(&msg_skip, cfg).expect("encode");
732
733 let touched_payload = TestHandlePayload {
734 handle: CuHandle::new_detached_with_mode(
735 vec![0xAA, 0xBB, 0xCC, 0xDD],
736 HandleContent::TouchedOnly,
737 ),
738 };
739 touched_payload.handle.mark_touched();
740 let msg_keep: CuMsg<TestHandlePayload> = CuMsg::new(Some(touched_payload));
741 let keep_bytes = encode_to_vec(&msg_keep, cfg).expect("encode");
742
743 assert_eq!(
744 skip_bytes[0], 0u8,
745 "first byte must be the no-payload presence tag for an untouched TouchedOnly handle"
746 );
747 assert_eq!(
748 keep_bytes[0], 1u8,
749 "first byte must be the payload-present tag once the handle was touched"
750 );
751 assert!(
752 keep_bytes.len() > skip_bytes.len(),
753 "touched encoding ({} bytes) must include payload content; skip is {} bytes",
754 keep_bytes.len(),
755 skip_bytes.len()
756 );
757 }
758
759 #[cfg(not(feature = "reflect"))]
762 #[test]
763 fn test_encode_keeps_payload_for_default_mode() {
764 use crate::pool::{CuHandle, HandleContent};
765 let cfg = config::standard();
766
767 let payload = TestHandlePayload {
768 handle: CuHandle::new_detached_with_mode(vec![1, 2, 3], HandleContent::All),
769 };
770 let msg: CuMsg<TestHandlePayload> = CuMsg::new(Some(payload));
771 let bytes = encode_to_vec(&msg, cfg).expect("encode");
772 assert_eq!(
773 bytes[0], 1u8,
774 "default (HandleContent::All) must keep emitting the payload"
775 );
776 }
777}