typed.rs
cdk-rsx/crates/cdk-rsx-reactor/src/typed.rs
1//! Concrete codecs meet typed handlers before transport erases payload types.2use crate::{3 Address, ReactorView,4 wire::{Context, Decision, Origin, PAYLOAD_LIMITS, SendError, WorkPriority},5};6use crate::{Error, Result};7use cdk_rsx::wire::{8 evolve::{decode_payload, encode_payload},9 upstream::Evolving,10};11use serde::{Serialize, de::DeserializeOwned};12use std::marker::PhantomData;13pub struct Endpoint<I, O> {14 pub route: &'static str,15 marker: PhantomData<fn(I) -> O>,16}17impl<I, O> Copy for Endpoint<I, O> {}18impl<I, O> Clone for Endpoint<I, O> {19 fn clone(&self) -> Self {20 *self21 }22}23impl<I, O> Endpoint<I, O> {24 pub const fn new(route: &'static str) -> Self {25 Self {26 route,27 marker: PhantomData,28 }29 }3031 fn dispatch_with(32 context: Context,33 input: Result<I>,34 encode: impl FnOnce(&O) -> Result<Vec<u8>>,35 handler: impl FnOnce(Context, I) -> Result<Decision<O>>,36 ) -> Result<Decision<Vec<u8>>> {37 let Ok(input) = input else {38 return Ok(Decision::Blocked);39 };40 match handler(context, input)? {41 Decision::Reply(value) => Ok(Decision::Reply(encode(&value)?)),42 Decision::Later => Ok(Decision::Later),43 Decision::Blocked => Ok(Decision::Blocked),44 }45 }46}47impl<I: Serialize + DeserializeOwned, O: Serialize + DeserializeOwned> Endpoint<I, O> {48 pub fn encode(&self, input: &I) -> Result<Vec<u8>> {49 cdk_rsx::wire::encode(input, PAYLOAD_LIMITS)50 .map_err(|_| Error::InvalidInput("Reactor input encoding"))51 }52 pub fn decode(&self, output: &[u8]) -> Result<O> {53 cdk_rsx::wire::decode::<O>(output, PAYLOAD_LIMITS)54 .map_err(|_| Error::InvalidInput("Reactor output decoding"))55 }56 pub fn dispatch(57 &self,58 context: Context,59 bytes: &[u8],60 handler: impl FnOnce(Context, I) -> Result<Decision<O>>,61 ) -> Result<Decision<Vec<u8>>> {62 Self::dispatch_with(63 context,64 cdk_rsx::wire::decode(bytes, PAYLOAD_LIMITS)65 .map_err(|_| Error::InvalidInput("Reactor input decoding")),66 |value| {67 cdk_rsx::wire::encode(value, PAYLOAD_LIMITS)68 .map_err(|_| Error::InvalidInput("Reactor output encoding"))69 },70 handler,71 )72 }73 pub fn request(74 &self,75 reactor: &ReactorView<'_, cdk_rsx_store::Scope<'_>>,76 destination: cdk_rsx::Principal,77 priority: WorkPriority,78 origin: Origin,79 input: &I,80 expires_at: Option<u64>,81 now: u64,82 ) -> Result<std::result::Result<Address, SendError>> {83 reactor.request_encoded_until(84 destination,85 priority,86 origin,87 self.route,88 reactor.runtime_handle().reader_version,89 self.encode(input)?,90 expires_at,91 now,92 )93 }94}9596impl<I: for<'de> Evolving<'de>, O: Evolving<'static>> Endpoint<I, O> {97 /// Decode the request's evolution projection and encode the declared reply type.98 pub fn dispatch_evolving(99 &self,100 context: Context,101 bytes: &[u8],102 handler: impl FnOnce(Context, I) -> Result<Decision<O>>,103 ) -> Result<Decision<Vec<u8>>> {104 Self::dispatch_with(context, decode_evolving(bytes), encode_evolving, handler)105 }106}107108/// Encode an evolving route value, including its nested projections.109/// Reactor supplies route selection and Wire manages staging under the route's limits.110pub fn encode_evolving<'de, T: Evolving<'de>>(value: &T) -> Result<Vec<u8>> {111 encode_payload(value, PAYLOAD_LIMITS)112 .map_err(|_| Error::InvalidInput("Reactor evolving payload encoding"))113}114115/// Admit one complete route value using the DTO's evolution projection.116pub fn decode_evolving<'de, T: Evolving<'de>>(bytes: &'de [u8]) -> Result<T> {117 decode_payload(bytes, PAYLOAD_LIMITS)118 .map_err(|_| Error::InvalidInput("Reactor evolving payload decoding"))119}120121/// Endpoint input/output mismatches are compiler errors.122/// ```compile_fail123/// use cdk_rsx_reactor::typed::Endpoint;124/// let endpoint = Endpoint::<u64,u64>::new("counter");125/// endpoint.encode(&"wrong input");126/// ```127/// Applications cannot select the library Control lane for requests.128/// ```compile_fail129/// use cdk_rsx_reactor::WorkPriority;130/// let priority = WorkPriority::Control;131/// ```132pub struct TypeSafety;133134#[cfg(test)]135mod tests {136 use super::{decode_evolving, encode_evolving};137138 #[derive(Debug, PartialEq, cdk_rsx::wire::upstream::Wire)]139 #[wire(crate = "cdk_rsx::wire::upstream")]140 struct Number(u8);141142 #[derive(Debug, PartialEq, cdk_rsx::wire::upstream::Wire)]143 #[wire(crate = "cdk_rsx::wire::upstream")]144 struct Counter {145 current: u8,146 #[wire(id = 7)]147 previous: Option<u8>,148 }149150 #[derive(Debug, PartialEq, cdk_rsx::wire::upstream::Wire)]151 #[wire(crate = "cdk_rsx::wire::upstream")]152 struct Request<Reading> {153 reading: Reading,154 }155156 #[test]157 fn evolving_route_validates_and_skips_unknown_extensions() {158 // Core u8 followed by a length-prefixed extension block.159 assert_eq!(encode_evolving(&Number(11)).unwrap(), [11, 0]);160 assert_eq!(decode_evolving::<Number>(&[11, 0]).unwrap(), Number(11));161 assert_eq!(162 decode_evolving::<Number>(&[11, 3, 7, 1, 255]).unwrap(),163 Number(11)164 );165 for malformed in [166 &[11][..], // absent block167 &[11, 3, 7, 2, 255], // truncated field span168 &[11, 4, 7, 0, 7, 0], // duplicate field ID169 &[11, 0, 0], // trailing bytes170 ] {171 assert!(decode_evolving::<Number>(malformed).is_err());172 }173 }174175 #[test]176 fn evolving_route_projects_added_fields_inside_a_request() {177 let old = Request {178 reading: Number(11),179 };180 let sent = encode_evolving(&old).unwrap();181 let new: Request<Counter> = decode_evolving(&sent).unwrap();182 assert_eq!(183 new.reading,184 Counter {185 current: 11,186 previous: None187 }188 );189190 let new = Request {191 reading: Counter {192 current: 12,193 previous: Some(11),194 },195 };196 let sent = encode_evolving(&new).unwrap();197 assert_eq!(sent, [12, 3, 7, 1, 11, 0]);198 assert_eq!(199 decode_evolving::<Request<Number>>(&sent).unwrap(),200 Request {201 reading: Number(12)202 }203 );204 }205}