Simplify hook runtime state

Remove the unused pending-hook layer and dead protocol trait wrappers, and resolve active hooks through a direct active-only flow with peer-side indexing instead of scan-based recovery.
This commit is contained in:
Michael Mikovsky
2026-04-25 11:57:37 -06:00
parent 7b5b148ef3
commit 62b22be39f
8 changed files with 53 additions and 291 deletions
+2 -3
View File
@@ -1,12 +1,11 @@
//! # UnShell Core //! # UnShell Core
//! //!
//! This crate implements the UnShell protocol as a pure, `no_std` library. //! This crate implements the UnShell protocol as a pure, `no_std` library.
//! It provides a trait-based architecture for routed endpoint communication //! It provides routed endpoint communication using an explicit tree topology.
//! using an explicit tree topology.
//! //!
//! ## Architecture //! ## Architecture
//! //!
//! - [`protocol`] - Wire types, framing, stateless validation, routing/runtime, and implementation traits. //! - [`protocol`] - Wire types, framing, stateless validation, and routing/runtime.
//! //!
//! The library requires `alloc` for path and payload management. //! The library requires `alloc` for path and payload management.
-2
View File
@@ -4,7 +4,6 @@
pub mod codec; pub mod codec;
pub mod introspection; pub mod introspection;
pub mod traits;
pub mod tree; pub mod tree;
mod types; mod types;
pub mod validation; pub mod validation;
@@ -16,7 +15,6 @@ pub use codec::{
FrameBytes, FrameCodec, FrameError, ParsedFrame, RkyvCodec, deserialize_archived_bytes, FrameBytes, FrameCodec, FrameError, ParsedFrame, RkyvCodec, deserialize_archived_bytes,
}; };
pub use introspection::{EndpointIntrospection, LeafIntrospection, LeafIntrospectionSummary}; pub use introspection::{EndpointIntrospection, LeafIntrospection, LeafIntrospectionSummary};
pub use traits::{HookStore, LeafMetadata, PacketFraming, PacketProcessor, RouteResolution};
pub use types::{ pub use types::{
CallMessage, DataMessage, FaultMessage, HookTarget, PacketHeader, PacketType, ProtocolFault, CallMessage, DataMessage, FaultMessage, HookTarget, PacketHeader, PacketType, ProtocolFault,
}; };
-167
View File
@@ -1,167 +0,0 @@
//! Protocol implementation traits exposed by the core crate.
//!
//! These traits collect the core contracts needed to plug framing, routing,
//! hook storage, leaf metadata, and packet processing into an implementation.
use alloc::{string::String, vec::Vec};
use super::{
FrameBytes, FrameCodec, LeafIntrospection, LeafIntrospectionSummary,
tree::{
ActiveHook, Endpoint, EndpointError, EndpointOutcome, HookConflict, HookKey, HookTable,
Ingress, LeafNode, LeafSpec, PendingHook, RouteProvider,
},
};
/// Packet framing contract for the canonical wire format.
pub trait PacketFraming: FrameCodec {}
impl<T> PacketFraming for T where T: FrameCodec + ?Sized {}
/// Route resolution contract for endpoint path delivery.
pub trait RouteResolution: RouteProvider {}
impl<T> RouteResolution for T where T: RouteProvider + ?Sized {}
/// Hook storage contract for pending and active protocol flows.
pub trait HookStore {
/// Allocates a hook identifier scoped to `return_path`.
fn allocate_hook_id(&mut self, return_path: &[String]) -> u64;
/// Inserts a hook created by an incoming call before the peer is confirmed.
fn insert_pending(&mut self, pending: PendingHook) -> Result<(), HookConflict>;
/// Inserts an already-established hook flow.
fn insert_active(&mut self, active: ActiveHook) -> Result<(), HookConflict>;
/// Promotes a pending hook once the responding peer is known.
fn activate_pending(&mut self, key: &HookKey, peer_path: Vec<String>) -> Option<()>;
/// Removes a pending hook.
fn remove_pending(&mut self, key: &HookKey) -> Option<PendingHook>;
/// Removes an active hook.
fn remove_active(&mut self, key: &HookKey) -> Option<ActiveHook>;
/// Returns immutable access to a pending hook.
fn pending(&self, key: &HookKey) -> Option<&PendingHook>;
/// Returns immutable access to an active hook.
fn active(&self, key: &HookKey) -> Option<&ActiveHook>;
/// Returns mutable access to an active hook.
fn active_mut(&mut self, key: &HookKey) -> Option<&mut ActiveHook>;
}
impl HookStore for HookTable {
fn allocate_hook_id(&mut self, return_path: &[String]) -> u64 {
HookTable::allocate_hook_id(self, return_path)
}
fn insert_pending(&mut self, pending: PendingHook) -> Result<(), HookConflict> {
HookTable::insert_pending(self, pending)
}
fn insert_active(&mut self, active: ActiveHook) -> Result<(), HookConflict> {
HookTable::insert_active(self, active)
}
fn activate_pending(&mut self, key: &HookKey, peer_path: Vec<String>) -> Option<()> {
HookTable::activate_pending(self, key, peer_path)
}
fn remove_pending(&mut self, key: &HookKey) -> Option<PendingHook> {
HookTable::remove_pending(self, key)
}
fn remove_active(&mut self, key: &HookKey) -> Option<ActiveHook> {
HookTable::remove_active(self, key)
}
fn pending(&self, key: &HookKey) -> Option<&PendingHook> {
HookTable::pending(self, key)
}
fn active(&self, key: &HookKey) -> Option<&ActiveHook> {
HookTable::active(self, key)
}
fn active_mut(&mut self, key: &HookKey) -> Option<&mut ActiveHook> {
HookTable::active_mut(self, key)
}
}
/// Leaf metadata contract used for protocol discovery payloads.
pub trait LeafMetadata {
/// Returns the leaf name exposed in routing and introspection.
fn leaf_name(&self) -> &str;
/// Returns the supported canonical procedure identifiers.
fn procedures(&self) -> &[String];
/// Builds the compact endpoint-wide discovery record for this leaf.
fn summary(&self) -> LeafIntrospectionSummary {
LeafIntrospectionSummary {
leaf_name: self.leaf_name().into(),
procedures: self.procedures().to_vec(),
}
}
/// Builds the full leaf-specific discovery payload.
fn introspection(&self) -> LeafIntrospection {
LeafIntrospection {
leaf_name: self.leaf_name().into(),
procedures: self.procedures().to_vec(),
}
}
}
impl LeafMetadata for LeafSpec {
fn leaf_name(&self) -> &str {
&self.name
}
fn procedures(&self) -> &[String] {
&self.procedures
}
}
impl LeafMetadata for LeafNode {
fn leaf_name(&self) -> &str {
&self.name
}
fn procedures(&self) -> &[String] {
&self.procedures
}
}
/// Packet processor and local runtime contract for framed protocol traffic.
pub trait PacketProcessor {
/// Returns the endpoint path that owns this processor.
fn path(&self) -> &[String];
/// Receives one framed packet from the given ingress side.
fn receive(
&mut self,
ingress: &Ingress,
frame: FrameBytes,
) -> Result<EndpointOutcome, EndpointError>;
}
impl<T> PacketProcessor for T
where
T: Endpoint + ?Sized,
{
fn path(&self) -> &[String] {
Endpoint::path(self)
}
fn receive(
&mut self,
ingress: &Ingress,
frame: FrameBytes,
) -> Result<EndpointOutcome, EndpointError> {
Endpoint::receive(self, ingress, frame)
}
}
-1
View File
@@ -63,7 +63,6 @@ impl ProtocolEndpoint {
peer_path: header.dst_path.clone(), peer_path: header.dst_path.clone(),
procedure_id: call.procedure_id.clone(), procedure_id: call.procedure_id.clone(),
dst_leaf: header.dst_leaf.clone(), dst_leaf: header.dst_leaf.clone(),
peer_finished: false,
}) })
.is_err() .is_err()
{ {
+11 -36
View File
@@ -23,7 +23,6 @@ impl ProtocolEndpoint {
return Ok(EndpointOutcome::dropped()); return Ok(EndpointOutcome::dropped());
}; };
self.hooks.remove_pending(&key);
self.hooks.remove_active(&key); self.hooks.remove_active(&key);
let header = PacketHeader { let header = PacketHeader {
@@ -52,28 +51,12 @@ impl ProtocolEndpoint {
message: DataMessage, message: DataMessage,
) -> Result<EndpointOutcome, EndpointError> { ) -> Result<EndpointOutcome, EndpointError> {
let hook_id = header.hook_id.expect("validated"); let hook_id = header.hook_id.expect("validated");
// The hook host can address its hook directly with `self.path + hook_id`. let Some(key) = self
// A non-host peer only knows the hook id it was given earlier, so it must
// recover the host-scoped key from active state using its validated path.
let key = self
.hooks .hooks
.active(&HookKey::new(self.path.clone(), hook_id)) .resolve_active_key(&self.path, hook_id, &header.src_path)
.map(|_| HookKey::new(self.path.clone(), hook_id)) else {
.or_else(|| { return Ok(EndpointOutcome::dropped());
self.hooks };
.find_active_key_by_peer(hook_id, &header.src_path)
})
.unwrap_or_else(|| HookKey::new(self.path.clone(), hook_id));
if self.hooks.active(&key).is_none() {
let matches = self.hooks.pending(&key).is_some_and(|pending| {
pending.caller_src_path == header.src_path
&& pending.procedure_id == message.procedure_id
});
if matches {
self.hooks.activate_pending(&key, header.src_path.clone());
}
}
let Some(active) = self.hooks.active(&key) else { let Some(active) = self.hooks.active(&key) else {
return Ok(EndpointOutcome::dropped()); return Ok(EndpointOutcome::dropped());
@@ -81,7 +64,6 @@ impl ProtocolEndpoint {
if active.peer_path != header.src_path { if active.peer_path != header.src_path {
self.hooks.remove_active(&key); self.hooks.remove_active(&key);
self.hooks.remove_pending(&key);
return Ok(EndpointOutcome::event(LocalEvent::Fault { return Ok(EndpointOutcome::event(LocalEvent::Fault {
header: PacketHeader { header: PacketHeader {
packet_type: PacketType::Fault, packet_type: PacketType::Fault,
@@ -113,22 +95,15 @@ impl ProtocolEndpoint {
header: PacketHeader, header: PacketHeader,
message: FaultMessage, message: FaultMessage,
) -> Result<EndpointOutcome, EndpointError> { ) -> Result<EndpointOutcome, EndpointError> {
let key = HookKey::new(self.path.clone(), header.hook_id.expect("validated")); let Some(key) = self.hooks.resolve_active_key(
let matches = self &self.path,
.hooks header.hook_id.expect("validated"),
.active(&key) &header.src_path,
.is_some_and(|active| active.peer_path == header.src_path) ) else {
|| self
.hooks
.pending(&key)
.is_some_and(|pending| pending.caller_src_path == header.src_path);
if !matches {
return Ok(EndpointOutcome::dropped()); return Ok(EndpointOutcome::dropped());
} };
self.hooks.remove_active(&key); self.hooks.remove_active(&key);
self.hooks.remove_pending(&key);
Ok(EndpointOutcome::event(LocalEvent::Fault { header, message })) Ok(EndpointOutcome::event(LocalEvent::Fault { header, message }))
} }
-1
View File
@@ -65,7 +65,6 @@ impl ProtocolEndpoint {
peer_path: header.src_path.clone(), peer_path: header.src_path.clone(),
procedure_id: message.procedure_id.clone(), procedure_id: message.procedure_id.clone(),
dst_leaf: header.dst_leaf.clone(), dst_leaf: header.dst_leaf.clone(),
peer_finished: false,
}) })
.is_err() .is_err()
{ {
+39 -80
View File
@@ -22,16 +22,6 @@ impl HookKey {
} }
} }
/// Pending hook context created by a received call.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PendingHook {
pub caller_src_path: Vec<String>,
pub return_path: Vec<String>,
pub hook_id: u64,
pub procedure_id: String,
pub dst_leaf: Option<String>,
}
/// Active hook context used for ordinary data traffic. /// Active hook context used for ordinary data traffic.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct ActiveHook { pub struct ActiveHook {
@@ -40,7 +30,13 @@ pub struct ActiveHook {
pub peer_path: Vec<String>, pub peer_path: Vec<String>,
pub procedure_id: String, pub procedure_id: String,
pub dst_leaf: Option<String>, pub dst_leaf: Option<String>,
pub peer_finished: bool, }
/// Peer-scoped index key used by the non-host side of a hook.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct PeerHookKey {
hook_id: u64,
peer_path: Vec<String>,
} }
/// Duplicate hook insertion error. /// Duplicate hook insertion error.
@@ -50,16 +46,16 @@ pub struct HookConflict;
/// Durable hook state tables. /// Durable hook state tables.
#[derive(Debug)] #[derive(Debug)]
pub struct HookTable { pub struct HookTable {
pending: BTreeMap<HookKey, PendingHook>,
active: BTreeMap<HookKey, ActiveHook>, active: BTreeMap<HookKey, ActiveHook>,
active_by_peer: BTreeMap<PeerHookKey, HookKey>,
next_id: u64, next_id: u64,
} }
impl Default for HookTable { impl Default for HookTable {
fn default() -> Self { fn default() -> Self {
Self { Self {
pending: BTreeMap::new(),
active: BTreeMap::new(), active: BTreeMap::new(),
active_by_peer: BTreeMap::new(),
next_id: 1, next_id: 1,
} }
} }
@@ -77,57 +73,29 @@ impl HookTable {
id id
} }
/// Inserts a pending hook created by an inbound call.
pub fn insert_pending(&mut self, pending: PendingHook) -> Result<(), HookConflict> {
let key = HookKey::new(pending.return_path.clone(), pending.hook_id);
if self.pending.contains_key(&key) || self.active.contains_key(&key) {
return Err(HookConflict);
}
self.pending.insert(key, pending);
Ok(())
}
/// Inserts an already-active hook flow. /// Inserts an already-active hook flow.
pub fn insert_active(&mut self, active: ActiveHook) -> Result<(), HookConflict> { pub fn insert_active(&mut self, active: ActiveHook) -> Result<(), HookConflict> {
let key = HookKey::new(active.return_path.clone(), active.hook_id); let key = HookKey::new(active.return_path.clone(), active.hook_id);
if self.pending.contains_key(&key) || self.active.contains_key(&key) { let peer_key = PeerHookKey {
hook_id: active.hook_id,
peer_path: active.peer_path.clone(),
};
if self.active.contains_key(&key) || self.active_by_peer.contains_key(&peer_key) {
return Err(HookConflict); return Err(HookConflict);
} }
self.active_by_peer.insert(peer_key, key.clone());
self.active.insert(key, active); self.active.insert(key, active);
Ok(()) Ok(())
} }
/// Promotes a pending hook into the active table once its peer is known.
pub fn activate_pending(&mut self, key: &HookKey, peer_path: Vec<String>) -> Option<()> {
let pending = self.pending.remove(key)?;
self.active.insert(
key.clone(),
ActiveHook {
return_path: pending.return_path,
hook_id: pending.hook_id,
peer_path,
procedure_id: pending.procedure_id,
dst_leaf: pending.dst_leaf,
peer_finished: false,
},
);
Some(())
}
/// Removes a pending hook entry.
pub fn remove_pending(&mut self, key: &HookKey) -> Option<PendingHook> {
self.pending.remove(key)
}
/// Removes an active hook entry. /// Removes an active hook entry.
pub fn remove_active(&mut self, key: &HookKey) -> Option<ActiveHook> { pub fn remove_active(&mut self, key: &HookKey) -> Option<ActiveHook> {
self.active.remove(key) let active = self.active.remove(key)?;
} self.active_by_peer.remove(&PeerHookKey {
hook_id: active.hook_id,
/// Returns a pending hook by its host-scoped key. peer_path: active.peer_path.clone(),
#[must_use] });
pub fn pending(&self, key: &HookKey) -> Option<&PendingHook> { Some(active)
self.pending.get(key)
} }
/// Returns an active hook by its host-scoped key. /// Returns an active hook by its host-scoped key.
@@ -136,34 +104,25 @@ impl HookTable {
self.active.get(key) self.active.get(key)
} }
/// Returns mutable access to an active hook by its host-scoped key. /// Resolves one active hook key from either the host side or the peer side.
pub fn active_mut(&mut self, key: &HookKey) -> Option<&mut ActiveHook> {
self.active.get_mut(key)
}
/// Finds an active hook key for a non-host peer receiving continued data.
///
/// Rationale: `hook_id` is scoped to the hook host, so a subordinate peer
/// cannot derive the full key from the packet header alone. The peer uses
/// its already-validated active state to recover the host-scoped key.
pub fn find_active_key_by_peer(&self, hook_id: u64, peer_path: &[String]) -> Option<HookKey> {
let mut matching_keys = self
.active
.iter()
.filter(|(_key, active)| active.hook_id == hook_id && active.peer_path == peer_path)
.map(|(key, _)| key.clone());
let key = matching_keys.next()?;
if matching_keys.next().is_some() {
return None;
}
Some(key)
}
/// Returns the number of pending hooks.
#[must_use] #[must_use]
pub fn pending_len(&self) -> usize { pub fn resolve_active_key(
self.pending.len() &self,
return_path: &[String],
hook_id: u64,
peer_path: &[String],
) -> Option<HookKey> {
let host_key = HookKey::new(return_path.to_vec(), hook_id);
if self.active.contains_key(&host_key) {
return Some(host_key);
}
self.active_by_peer
.get(&PeerHookKey {
hook_id,
peer_path: peer_path.to_vec(),
})
.cloned()
} }
/// Returns the number of active hooks. /// Returns the number of active hooks.
+1 -1
View File
@@ -8,7 +8,7 @@ pub use endpoint::{
ChildRoute, ConnectionState, Endpoint, EndpointError, EndpointOutcome, Ingress, LeafSpec, ChildRoute, ConnectionState, Endpoint, EndpointError, EndpointOutcome, Ingress, LeafSpec,
LocalEvent, ProtocolEndpoint, LocalEvent, ProtocolEndpoint,
}; };
pub use hook::{ActiveHook, HookConflict, HookKey, HookTable, PendingHook}; pub use hook::{ActiveHook, HookConflict, HookKey, HookTable};
pub use routing::{ pub use routing::{
DefaultRouteProvider, LeafNode, RouteDecision, RouteProvider, TreeNode, is_prefix, DefaultRouteProvider, LeafNode, RouteDecision, RouteProvider, TreeNode, is_prefix,
route_destination, route_destination,