types.rs
cdk-rsx/crates/cdk-rsx-takt/src/types.rs
1//! Statically compiled graph contracts. No functions or registry names are retained in graph records.2use crate::PayloadSize;3use crate::memory::current::SavedRequest;4pub use crate::memory::current::{5 BlockReason, EventKind, ExternalAddress, Failure, Key, PayloadContract, Phase, Priority,6 Safety, TraceEvent, Transport,7};8pub use cdk_rsx::Principal;9use std::rc::Rc;1011#[derive(Clone, Debug, PartialEq, Eq)]12pub struct Request {13 pub canister: Principal,14 pub caller: Principal,15 pub route: String,16 pub reader_version: u32,17 pub args: Rc<[u8]>,18 pub expires_at: Option<u64>,19 pub transport: Transport,20 pub priority: Priority,21}22impl Request {23 /// Capture before publishing the first effect. Subsequent attempts share the24 /// resulting retained Rc; they do not recapture or refresh request metadata.25 pub(crate) fn retain(self) -> SavedRequest {26 SavedRequest {27 canister: self.canister,28 caller: self.caller,29 route: self.route.into(),30 reader_version: self.reader_version,31 args: cdk_rsx_collections::nyxus::SharedSlice::copy_from_slice(&self.args),32 expires_at: self.expires_at.into(),33 transport: self.transport,34 priority: self.priority,35 }36 }37}38impl SavedRequest {39 /// An inspection DTO; the transport consumes saved fields directly instead.40 pub(crate) fn snapshot(&self) -> Request {41 Request {42 canister: self.canister,43 caller: self.caller,44 route: self.route.as_str().to_owned(),45 reader_version: self.reader_version,46 args: Rc::from(self.args.as_slice()),47 expires_at: self.expires_at.into_option(),48 transport: self.transport,49 priority: self.priority,50 }51 }52}53impl PayloadSize for Request {54 fn payload_bytes(&self) -> usize {55 // Source request admission layout: eight framed fields, fixed56 // principals, two enum tags, and the optional absolute expiry.57 173usize58 .saturating_add(self.route.len())59 .saturating_add(self.args.len())60 .saturating_add(if self.expires_at.is_some() { 8 } else { 0 })61 }62}63#[derive(Clone, Debug, PartialEq, Eq)]64pub enum Known<D, E> {65 Ok(D),66 Err(E),67}68#[derive(Clone, Debug, PartialEq, Eq)]69pub enum Reply<D, E> {70 Ok(D),71 Err(E),72 Unknown,73 Resolved(Known<D, E>),74}75#[derive(Clone, Debug, PartialEq, Eq)]76pub enum Status<D, E> {77 Running,78 DefinitionChanged,79 Succeeded(D),80 Failed(Failure<E>),81}82#[derive(Clone, Copy, Debug, PartialEq, Eq)]83pub struct Settings {84 pub max_pending: u32,85 pub max_concurrent: u32,86 pub max_nodes: u32,87 pub max_results: u32,88 pub result_retention_nanos: u64,89 pub max_data_bytes: u32,90 pub max_error_bytes: u32,91 pub trace_events: u32,92}93impl Default for Settings {94 fn default() -> Self {95 Self {96 max_pending: 64,97 max_concurrent: 10,98 max_nodes: 32,99 max_results: 64,100 result_retention_nanos: 3_600_000_000_000,101 max_data_bytes: 16384,102 max_error_bytes: 1024,103 trace_events: 0,104 }105 }106}107#[derive(Clone, Copy, Debug, PartialEq, Eq)]108pub struct RuntimeSettings {109 pub max_pending: u32,110 pub max_concurrent: u32,111 pub max_physical: u32,112}113impl Default for RuntimeSettings {114 fn default() -> Self {115 Self {116 max_pending: 256,117 max_concurrent: 10,118 max_physical: 40,119 }120 }121}122pub type NodeId = u32;123pub type ExecutionId = u64;124/// All runtime times are absolute IC nanoseconds, never wall-clock durations.125pub type Timestamp = u64;126127#[derive(Clone, Copy, Debug)]128pub struct Context {129 pub key: Key,130 pub attempt: u32,131 pub now: Timestamp,132 pub call_timeout_millis: u32,133 pub next_event: Option<Key>,134}135#[derive(Clone, Copy, Debug, PartialEq, Eq)]136pub enum NodeKind {137 Control,138 Local,139 Remote,140 Await,141}142143#[derive(Clone, Copy, Debug, PartialEq, Eq)]144pub struct Backoff {145 pub interval_millis: u64,146 pub multiplier: u32,147 pub max_delay_millis: u64,148 pub max_retries: u32,149}150impl Backoff {151 pub const fn delay_nanos(self, used: u32) -> u64 {152 let mut delay = self.interval_millis;153 let mut count = 0;154 while count < used && delay < self.max_delay_millis && self.multiplier > 1 {155 delay = delay.saturating_mul(self.multiplier as u64);156 count += 1;157 }158 if delay > self.max_delay_millis {159 delay = self.max_delay_millis;160 }161 delay.saturating_mul(1_000_000)162 }163}164#[derive(Clone, Copy, Debug, PartialEq, Eq)]165pub enum Exhausted {166 Fail,167 Pause,168}169#[derive(Clone, Copy, Debug)]170pub struct TaskPolicy {171 pub safety: Safety,172 pub timeout_millis: u64,173 pub call_timeout_millis: u32,174 pub on_exhausted: Exhausted,175}176impl Default for TaskPolicy {177 fn default() -> Self {178 Self {179 safety: Safety::Reconcile,180 timeout_millis: 30_000,181 call_timeout_millis: 10_000,182 on_exhausted: Exhausted::Fail,183 }184 }185}186187pub enum Step<D, E> {188 Next {189 node: NodeId,190 data: D,191 },192 Succeed(D),193 Fail(E),194 Local {195 reply: Known<D, E>,196 next: Option<NodeId>,197 },198 Handler {199 next: Option<NodeId>,200 },201 Remote {202 request: Request,203 next: Option<NodeId>,204 },205 RemoteReply {206 reply: Reply<D, E>,207 next: Option<NodeId>,208 },209 Wait {210 until: Timestamp,211 next: Option<NodeId>,212 data: D,213 },214 Await {215 producer: Principal,216 next: Option<NodeId>,217 },218 Parallel {219 branches: Vec<(NodeId, D)>,220 next: Option<NodeId>,221 },222}223224/// Generated definitions call typed application functions in numeric match arms.225/// Implementations may borrow scoped services; neither this value nor its226/// closures survive a message. Business state is accessed only through services.227pub type ReplySink<D, E> = std::rc::Rc<dyn Fn(Reply<D, E>)>;228pub type HandlerFuture = std::pin::Pin<Box<dyn std::future::Future<Output = ()> + 'static>>;229230pub trait Definition {231 type Data: PayloadContract + PayloadSize + Clone;232 type Error: PayloadContract + PayloadSize + Clone;233 const ID: &'static str;234 const VERSION: u32;235 /// Build-time fingerprint of the function-free executable graph.236 const SIGNATURE: Option<[u8; 32]> = None;237 /// Explicit opt-in source/interpretation contract for local-work KEEP.238 /// Pin the complete step/reply/policy dependency closure and active cfg,239 /// including external business helpers that can affect pending execution.240 /// The root catalog must include this contract. A graph fingerprint alone241 /// does not pin function bodies. None keeps the ordinary full-drain policy.242 const LOCAL_UPGRADE_SOURCE: Option<[u8; 32]> = None;243 const START: NodeId;244 /// Optional pure, truthful payload bounds, fixed by the compiled definition.245 /// Function pointers let the engine bind the same contract for callbacks246 /// without retaining a scoped definition or allocating an erased closure.247 const DATA_BYTES: Option<fn(&Self::Data) -> usize> = None;248 const ERROR_BYTES: Option<fn(&Self::Error) -> usize> = None;249 fn kind(&self, _node: NodeId) -> NodeKind {250 NodeKind::Control251 }252 fn step(253 &self,254 node: NodeId,255 input: &Self::Data,256 context: &Context,257 ) -> Step<Self::Data, Self::Error>;258 fn policy(&self, _node: NodeId) -> TaskPolicy {259 TaskPolicy::default()260 }261 fn safe_until(&self, _node: NodeId, _input: &Self::Data) -> Option<Timestamp> {262 None263 }264 /// First matching rule owns its budget; an exhausted rule does not fall265 /// through to a later rule. At most sixteen rules are generated per node.266 fn retry_rule(&self, _node: NodeId, _failure: &Failure<Self::Error>) -> Option<(u8, Backoff)> {267 None268 }269 fn catch(270 &self,271 _node: NodeId,272 _input: &Self::Data,273 _failure: &Failure<Self::Error>,274 ) -> Option<(NodeId, Self::Data)> {275 None276 }277 fn reply(278 &self,279 _node: NodeId,280 _input: &Self::Data,281 _bytes: &[u8],282 _context: &Context,283 ) -> Reply<Self::Data, Self::Error> {284 Reply::Unknown285 }286 /// Construct an owned future; invoke the sink only when that future is polled.287 /// Reporting an early reply never ends the physical handler lifetime.288 fn handler(289 &self,290 _node: NodeId,291 _input: Self::Data,292 _context: Context,293 _reply: ReplySink<Self::Data, Self::Error>,294 ) -> Option<HandlerFuture> {295 None296 }297 fn event_source(&self, _node: NodeId, _input: &Self::Data) -> Option<Principal> {298 None299 }300 fn send_error(301 &self,302 _node: NodeId,303 _error: cdk_rsx_reactor::wire::SendError,304 ) -> Option<Self::Error> {305 None306 }307 fn event(308 &self,309 _node: NodeId,310 _input: &Self::Data,311 _producer: Principal,312 _bytes: &[u8],313 ) -> Option<Self::Data> {314 None315 }316 fn join(&self, _node: NodeId, input: &Self::Data, _branches: &[Self::Data]) -> Self::Data {317 input.clone()318 }319 /// The static target is used to allocate the successor visit address before320 /// a ScheduleWorkflow operation publishes its child request.321 fn next_event(&self, _node: NodeId) -> bool {322 false323 }324}325326pub(crate) const fn definition_signature<F: Definition>() -> (Option<[u8; 32]>, [u8; 32]) {327 match (F::SIGNATURE, F::LOCAL_UPGRADE_SOURCE) {328 (signature, None) => (signature, [0; 32]),329 (Some(graph), Some(source)) => {330 let identity = cdk_rsx_memory_abi::semantic_contract(331 "takt/local-upgrade-definition/v1",332 &[],333 &[graph, source],334 );335 (Some(identity), identity)336 }337 (None, Some(_)) => panic!("local-work KEEP source contract requires a graph signature"),338 }339}340341/// Bind-once services project one borrowed graph definition into the caller's342/// existing frame. The view ends before a handler future leaves the engine.343pub trait DefinitionFactory {344 type Data: PayloadContract + PayloadSize + Clone;345 type Error: PayloadContract + PayloadSize + Clone;346 type View<'a, 's>: Definition<Data = Self::Data, Error = Self::Error>347 where348 Self: 'a,349 's: 'a;350 fn view<'a, 's>(&'a self, scope: &'a cdk_rsx_store::Scope<'s>) -> Self::View<'a, 's>;351}352// Pure definitions need no service projection or allocation.353impl<F: Definition> DefinitionFactory for F {354 type Data = F::Data;355 type Error = F::Error;356 type View<'a, 's>357 = &'a F358 where359 F: 'a,360 's: 'a;361 fn view<'a, 's>(&'a self, _: &'a cdk_rsx_store::Scope<'s>) -> Self::View<'a, 's> {362 self363 }364}365impl<F: Definition + ?Sized> Definition for &F {366 type Data = F::Data;367 type Error = F::Error;368 const ID: &'static str = F::ID;369 const VERSION: u32 = F::VERSION;370 const SIGNATURE: Option<[u8; 32]> = F::SIGNATURE;371 const LOCAL_UPGRADE_SOURCE: Option<[u8; 32]> = F::LOCAL_UPGRADE_SOURCE;372 const START: NodeId = F::START;373 const DATA_BYTES: Option<fn(&Self::Data) -> usize> = F::DATA_BYTES;374 const ERROR_BYTES: Option<fn(&Self::Error) -> usize> = F::ERROR_BYTES;375 fn kind(&self, node: NodeId) -> NodeKind {376 (**self).kind(node)377 }378 fn step(379 &self,380 node: NodeId,381 input: &Self::Data,382 context: &Context,383 ) -> Step<Self::Data, Self::Error> {384 (**self).step(node, input, context)385 }386 fn policy(&self, node: NodeId) -> TaskPolicy {387 (**self).policy(node)388 }389 fn safe_until(&self, node: NodeId, input: &Self::Data) -> Option<Timestamp> {390 (**self).safe_until(node, input)391 }392 fn retry_rule(&self, node: NodeId, failure: &Failure<Self::Error>) -> Option<(u8, Backoff)> {393 (**self).retry_rule(node, failure)394 }395 fn catch(396 &self,397 node: NodeId,398 input: &Self::Data,399 failure: &Failure<Self::Error>,400 ) -> Option<(NodeId, Self::Data)> {401 (**self).catch(node, input, failure)402 }403 fn reply(404 &self,405 node: NodeId,406 input: &Self::Data,407 bytes: &[u8],408 context: &Context,409 ) -> Reply<Self::Data, Self::Error> {410 (**self).reply(node, input, bytes, context)411 }412 fn handler(413 &self,414 node: NodeId,415 input: Self::Data,416 context: Context,417 sink: ReplySink<Self::Data, Self::Error>,418 ) -> Option<HandlerFuture> {419 (**self).handler(node, input, context, sink)420 }421 fn event_source(&self, node: NodeId, input: &Self::Data) -> Option<Principal> {422 (**self).event_source(node, input)423 }424 fn send_error(425 &self,426 node: NodeId,427 error: cdk_rsx_reactor::wire::SendError,428 ) -> Option<Self::Error> {429 (**self).send_error(node, error)430 }431 fn event(432 &self,433 node: NodeId,434 input: &Self::Data,435 producer: Principal,436 bytes: &[u8],437 ) -> Option<Self::Data> {438 (**self).event(node, input, producer, bytes)439 }440 fn join(&self, node: NodeId, input: &Self::Data, branches: &[Self::Data]) -> Self::Data {441 (**self).join(node, input, branches)442 }443 fn next_event(&self, node: NodeId) -> bool {444 (**self).next_event(node)445 }446}447448#[derive(Clone, Debug, PartialEq, Eq, cdk_rsx::WireType, serde::Deserialize, serde::Serialize)]449pub enum Problem {450 Busy,451 PayloadTooLarge,452 Missing,453 Pending,454 StaleKey,455 NotBlocked,456 UnsafeRetry,457 InvalidEvent,458 DefinitionChanged,459 PendingCalls,460 PendingAddress,461}462pub type Outcome<T> = crate::Result<Result<T, Problem>>;463464#[derive(Clone, Copy, Debug)]465pub enum Delay {466 Millis(u64),467 Until(u64),468}469impl Delay {470 pub fn deadline(self, now: u64) -> u64 {471 match self {472 Self::Millis(ms) => now.saturating_add(ms.saturating_mul(1_000_000)),473 Self::Until(at) => at,474 }475 }476}477pub struct Event<I, O> {478 pub source: fn(&I) -> Principal,479 pub receive: fn(&I, &[u8]) -> Option<O>,480}481#[derive(Clone, Copy, Debug)]482pub struct ParticipantContract {483 pub id: &'static str,484 pub safety: Safety,485 pub evidence: Evidence,486}487#[derive(Clone, Copy, Debug, PartialEq, Eq)]488pub enum Evidence {489 Receipt,490 ReadOnly,491 Reconcile,492}493impl ParticipantContract {494 pub const fn validate(self) {495 assert!(496 !self.id.is_empty(),497 "participant contract ID cannot be empty"498 );499 if matches!(self.evidence, Evidence::ReadOnly) {500 assert!(501 matches!(self.safety, Safety::ReadOnly),502 "read evidence cannot authorize mutation"503 );504 }505 }506}507508/// A concrete carrier projection, checked by generated Rust at every graph edge.509pub struct Port<D, I> {510 pub put: fn(I) -> D,511 pub get: for<'a> fn(&'a D) -> Option<&'a I>,512}513impl<D, I> Copy for Port<D, I> {}514impl<D, I> Clone for Port<D, I> {515 fn clone(&self) -> Self {516 *self517 }518}519pub enum RemotePreparation<O, E> {520 Request(Request),521 Reply(Reply<O, E>),522}523pub trait RemoteOperation<D, E> {524 const SAFETY: Safety;525 type Input: Clone;526 type Output: Clone;527 fn input(&self) -> Port<D, Self::Input>;528 fn output(&self) -> Port<D, Self::Output>;529 fn prepare(&self, context: &Context, input: &Self::Input)530 -> RemotePreparation<Self::Output, E>;531 fn reply(&self, input: &Self::Input, bytes: &[u8], context: &Context)532 -> Reply<Self::Output, E>;533 fn safe_until(&self, _input: &Self::Input) -> Option<u64> {534 None535 }536}537pub fn map_reply<I, O, E>(reply: Reply<I, E>, output: impl FnOnce(I) -> O) -> Reply<O, E> {538 match reply {539 Reply::Ok(value) => Reply::Ok(output(value)),540 Reply::Err(error) => Reply::Err(error),541 Reply::Unknown => Reply::Unknown,542 Reply::Resolved(Known::Ok(value)) => Reply::Resolved(Known::Ok(output(value))),543 Reply::Resolved(Known::Err(error)) => Reply::Resolved(Known::Err(error)),544 }545}546547#[derive(Clone, Debug, PartialEq, Eq)]548pub struct InspectionField {549 pub name: String,550 pub text: String,551}552553/// Transient typed plans become one immutable, encoded request before sending.554pub enum RemotePlan<A, O, E> {555 Call { canister: Principal, args: A },556 Reply(Reply<O, E>),557}558pub enum DispatchPlan<A, O, E> {559 Dispatch {560 action: A,561 on_success: Box<dyn FnOnce(u64) -> O>,562 },563 Done(O),564 Reject(E),565}566#[derive(Clone, Copy, Debug, PartialEq, Eq)]567pub enum MethodKind {568 Update,569 Query,570}571/// Function-pointer invariance keeps the Wire request/reply types attached to572/// the method selected by generated Rust. No method registry is consulted.573pub struct Endpoint<I, O> {574 pub method: &'static str,575 pub kind: MethodKind,576 _types: core::marker::PhantomData<fn(I) -> O>,577}578impl<I, O> Endpoint<I, O> {579 pub const fn new(method: &'static str, kind: MethodKind) -> Self {580 Self {581 method,582 kind,583 _types: core::marker::PhantomData,584 }585 }586}587impl<I, O> Copy for Endpoint<I, O> {}588impl<I, O> Clone for Endpoint<I, O> {589 fn clone(&self) -> Self {590 *self591 }592}593#[derive(Clone, Copy, Debug)]594pub struct ReactorContext {595 pub reader_version: u32,596 pub priority: Priority,597 pub caller: Principal,598}599pub trait LocalOperation<D, E> {600 type Input: Clone;601 type Output: Clone;602 fn input(&self) -> Port<D, Self::Input>;603 fn output(&self) -> Port<D, Self::Output>;604 fn run(&self, context: &Context, input: &Self::Input) -> Known<Self::Output, E>;605 fn safe_until(&self, _input: &Self::Input) -> Option<u64> {606 None607 }608}609610#[cfg(feature = "tripwire-workload")]611pub use cdk_rsx_reactor::tripwire_codec::{decode as decode_message, encode as encode_message};612613/// Headerless Wire value inside an authenticated, route-bound Reactor frame.614#[cfg(not(feature = "tripwire-workload"))]615pub fn encode_message<T: serde::Serialize + ?Sized>(616 value: &T,617) -> Result<Vec<u8>, cdk_rsx::wire::Error> {618 cdk_rsx::wire::encode(value, cdk_rsx_reactor::wire::PAYLOAD_LIMITS)619}620#[cfg(not(feature = "tripwire-workload"))]621pub fn decode_message<T: serde::de::DeserializeOwned>(622 bytes: &[u8],623) -> Result<T, cdk_rsx::wire::Error> {624 cdk_rsx::wire::decode(bytes, cdk_rsx_reactor::wire::PAYLOAD_LIMITS)625}626627pub trait ReadOperation<D> {628 type Input: Clone;629 type Output: Clone;630 fn input(&self) -> Port<D, Self::Input>;631 fn output(&self) -> Port<D, Self::Output>;632 fn run(&self, input: &Self::Input) -> Self::Output;633}634pub trait TransformOperation<D>: ReadOperation<D> {}635impl<D, T: ReadOperation<D>> TransformOperation<D> for T {}636637#[derive(Clone, Copy)]638pub struct RetryPolicy<E> {639 pub when: fn(&E) -> bool,640 pub backoff: Backoff,641}642#[derive(Clone, Copy)]643pub struct Policy<E> {644 pub task: TaskPolicy,645 pub retry: Option<RetryPolicy<E>>,646}647648impl From<Priority> for cdk_rsx_reactor::WorkPriority {649 fn from(p: Priority) -> Self {650 match p {651 Priority::Interactive => Self::Interactive,652 Priority::Maintenance => Self::Maintenance,653 }654 }655}