Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(modules): add channel runtime module and test fixture support

Steven Enamakelab0803e3a145
diff --git a/crates/openhuman-core/src/modules/channel_runtime.rs b/crates/openhuman-core/src/modules/channel_runtime.rs
new file mode 100644
index 0000000000..90dbd0e579
--- /dev/null
+++ b/crates/openhuman-core/src/modules/channel_runtime.rs
@@ -0,0 +1,165 @@
+//! Identity-scoped channel objects and cancellation-safe callback ownership.
+
+use std::sync::{atomic::{AtomicBool, Ordering}, Arc};
+use std::time::Duration;
+use tokio::sync::Mutex;
+use tinybus::{Connection, ObjectPath, Proxy};
+use tinychannels_bus::{methods, ChannelRuntimeReservation, HOST_BUS_NAME, HOST_OBJECT_PATH, OBJECT_PATH};
+use super::client::{ModuleCallError, ModuleClient, ModuleObjectClient};
+
+const CLOSE_BUDGET: Duration = Duration::from_secs(15);
+
+/// Keeps a captured host adapter exported until the module acknowledges stop.
+#[derive(Clone)]
+pub(crate) struct ChannelRuntimeLease(Arc<LeaseState>);
+
+struct LeaseState {
+ object: ModuleObjectClient,
+ cleanup: Cleanup,
+ closing: Mutex<Option<tokio::task::JoinHandle<Result<(), ModuleCallError>>>>,
+ runtime: &'static super::host::ModuleRuntime,
+}
+
+#[derive(Clone)]
+struct Cleanup {
+ proxy: Proxy,
+ connection: Connection,
+ callback: ObjectPath,
+ handle: String,
+ closed: Arc<AtomicBool>,
+ reported: Arc<AtomicBool>,
+}
+
+impl Cleanup {
+ async fn run(&self) -> Result<(), ModuleCallError> {
+ if self.closed.load(Ordering::Acquire) {
+ return Ok(());
+ }
+ // Stop is idempotent. A transport deadline never licenses removal of
+ // the adapter: the module may still own listeners or pending sends.
+ let result: tinybus::Result<()> = self.proxy
+ .call_confidential(methods::STOP_RUNTIME, (self.handle.clone(),)).await;
+ result.map_err(|error| {
+ let record = super::registry::find("tinychannels").expect("registered channel module");
+ if !self.reported.swap(true, Ordering::AcqRel) {
+ super::client::report_proxy_failure(record, &error)
+ } else {
+ ModuleCallError::TransportFailed
+ }
+ })?;
+ self.connection.unserve(&self.callback).await;
+ self.closed.store(true, Ordering::Release);
+ Ok(())
+ }
+}
+
+impl Drop for LeaseState {
+ fn drop(&mut self) {
+ if self.cleanup.closed.load(Ordering::Acquire) {
+ return;
+ }
+ let pending = self.closing.get_mut().take();
+ let cleanup = self.cleanup.clone();
+ // Retain both the callback connection and its captured identity after
+ // cancellation or last-owner drop. Never abort a module's shutdown.
+ self.runtime.spawn(async move {
+ if let Some(pending) = pending {
+ if matches!(pending.await, Ok(Ok(()))) {
+ return;
+ }
+ }
+ loop {
+ if cleanup.run().await.is_ok() {
+ break;
+ }
+ tokio::time::sleep(Duration::from_secs(5)).await;
+ }
+ });
+ }
+}
+
+impl ChannelRuntimeLease {
+ pub(crate) async fn open(
+ client: ModuleClient,
+ callback: impl tinybus::service::Interface + 'static,
+ ) -> Result<Self, ModuleCallError> {
+ // This check performs lazy admission before starting any callback work.
+ let reservation: ChannelRuntimeReservation = client
+ .call_confidential("tinychannels", methods::RESERVE_RUNTIME, ()).await?;
+ validate_reservation(&reservation)?;
+ let runtime = super::host::runtime().await.map_err(|_| ModuleCallError::TransportFailed)?;
+ let (sender, receiver) = tokio::sync::oneshot::channel();
+ runtime.spawn(async move {
+ let result = Self::activate(client, reservation, callback, runtime).await;
+ // A dropped receiver drops the lease, which owns cleanup. The
+ // activation task itself is independent of the requesting runtime.
+ let _ = sender.send(result);
+ });
+ receiver.await.map_err(|_| ModuleCallError::TransportFailed)?
+ }
+
+ async fn activate(
+ client: ModuleClient,
+ reservation: ChannelRuntimeReservation,
+ callback: impl tinybus::service::Interface,
+ runtime: &'static super::host::ModuleRuntime,
+ ) -> Result<Self, ModuleCallError> {
+ let connection = runtime.connection().clone();
+ let callback_path = ObjectPath::new(&reservation.host_object_path)
+ .map_err(|_| ModuleCallError::ModuleFault)?;
+ let proxy = runtime.proxy(tinychannels_bus::BUS_NAME, OBJECT_PATH)
+ .map_err(|_| ModuleCallError::IncompatibleContract)?;
+ let cleanup = Cleanup {
+ proxy, connection: connection.clone(), callback: callback_path.clone(),
+ handle: reservation.handle.clone(), closed: Arc::new(AtomicBool::new(false)),
+ reported: Arc::new(AtomicBool::new(false)),
+ };
+ // Acquire an owned lease before exporting the adapter. Any subsequent
+ // failure follows the same acknowledged-stop path as explicit close.
+ let object = match client.object_client("tinychannels", &reservation.object_path).await {
+ Ok(object) => object,
+ Err(error) => {
+ runtime.spawn(async move { while cleanup.run().await.is_err() {
+ tokio::time::sleep(Duration::from_secs(5)).await;
+ }});
+ return Err(error);
+ }
+ };
+ let lease = Self(Arc::new(LeaseState { object, cleanup, closing: Mutex::new(None), runtime }));
+ connection.request_name(HOST_BUS_NAME).await.map_err(|_| ModuleCallError::TransportFailed)?;
+ connection.serve_at(callback_path, callback).await.map_err(|_| ModuleCallError::TransportFailed)?;
+ client.call_confidential::<()>("tinychannels", methods::START_RUNTIME, (reservation.handle,)).await?;
+ Ok(lease)
+ }
+
+ pub(crate) fn object(&self) -> &ModuleObjectClient { &self.0.object }
+
+ pub(crate) async fn close(&self) -> Result<(), ModuleCallError> {
+ if self.0.cleanup.closed.load(Ordering::Acquire) { return Ok(()); }
+ let mut closing = self.0.closing.lock().await;
+ if closing.is_none() {
+ let cleanup = self.0.cleanup.clone();
+ *closing = Some(self.0.runtime.spawn(async move { cleanup.run().await }));
+ }
+ let result = tokio::time::timeout(CLOSE_BUDGET, closing.as_mut().expect("cleanup worker"))
+ .await.map_err(|_| ModuleCallError::TransportFailed)?;
+ closing.take();
+ result.map_err(|_| ModuleCallError::TransportFailed)?
+ }
+}
+
+fn validate_reservation(reservation: &ChannelRuntimeReservation) -> Result<(), ModuleCallError> {
+ if reservation.handle.len() != 32
+ || !reservation.handle.bytes().all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
+ || reservation.object_path != format!("{OBJECT_PATH}/runtime_{}", reservation.handle)
+ || reservation.host_object_path != format!("{HOST_OBJECT_PATH}/runtime_{}", reservation.handle)
+ {
+ ModuleClient::report_malformed_reply("tinychannels");
+ return Err(ModuleCallError::ModuleFault);
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+#[path = "channel_runtime_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/modules/channel_runtime_tests.rs b/crates/openhuman-core/src/modules/channel_runtime_tests.rs
new file mode 100644
index 0000000000..df879f9a29
--- /dev/null
+++ b/crates/openhuman-core/src/modules/channel_runtime_tests.rs
@@ -0,0 +1,29 @@
+use super::*;
+
+fn reservation() -> ChannelRuntimeReservation {
+ let handle = "0123456789abcdef0123456789abcdef".to_string();
+ ChannelRuntimeReservation {
+ object_path: format!("{OBJECT_PATH}/runtime_{handle}"),
+ host_object_path: format!("{HOST_OBJECT_PATH}/runtime_{handle}"),
+ handle,
+ }
+}
+
+#[test]
+fn private_paths_must_belong_to_the_reserved_runtime() {
+ assert!(validate_reservation(&reservation()).is_ok());
+ for path in [HOST_OBJECT_PATH.to_string(), format!("{HOST_OBJECT_PATH}/runtime_ffffffffffffffffffffffffffffffff")] {
+ let mut value = reservation(); value.host_object_path = path;
+ assert_eq!(validate_reservation(&value), Err(ModuleCallError::ModuleFault));
+ }
+ let mut value = reservation(); value.object_path = OBJECT_PATH.to_string();
+ assert_eq!(validate_reservation(&value), Err(ModuleCallError::ModuleFault));
+}
+
+#[test]
+fn malformed_handles_cannot_replace_another_callback() {
+ for handle in ["", "../secret", "0123456789ABCDEF0123456789ABCDEF", "0123456789abcdef0123456789abcdef/other"] {
+ let mut value = reservation(); value.handle = handle.to_string();
+ assert_eq!(validate_reservation(&value), Err(ModuleCallError::ModuleFault));
+ }
+}
diff --git a/crates/openhuman-core/src/modules/client.rs b/crates/openhuman-core/src/modules/client.rs
index 14d759d568..33705cba7c 100644
--- a/crates/openhuman-core/src/modules/client.rs
+++ b/crates/openhuman-core/src/modules/client.rs
@@ -147,6 +147,16 @@ impl ModuleClient {
failure::report(record, failure::Reason::Disabled);
return Err(ModuleCallError::Unavailable);
}
+ #[cfg(test)]
+ if let Some(fixture) = &self.fixture {
+ let proxy = fixture.connection().proxy(
+ fixture.destination().as_str(),
+ object_path,
+ fixture.interface().as_str(),
+ ).map_err(|_| ModuleCallError::IncompatibleContract)?;
+ let proxy = self.timeout.map_or(proxy.clone(), |timeout| proxy.with_timeout(timeout));
+ return Ok(ModuleObjectClient { record, proxy });
+ }
super::ops::ensure_loaded(&self.config, module)
.await
.map_err(|_| ModuleCallError::Unavailable)?;
@@ -242,6 +252,7 @@ impl ModuleClient {
/// This stays crate-private so bus object identities do not become product
/// state or leak into logs and controller responses.
#[cfg(feature = "modules")]
+#[derive(Clone)]
pub(crate) struct ModuleObjectClient {
record: &'static super::types::ModuleRecord,
proxy: tinybus::Proxy,
diff --git a/crates/openhuman-core/src/modules/mod.rs b/crates/openhuman-core/src/modules/mod.rs
index cb7d147e19..daf23198d6 100644
--- a/crates/openhuman-core/src/modules/mod.rs
+++ b/crates/openhuman-core/src/modules/mod.rs
@@ -51,6 +51,8 @@ pub mod browser_task;
mod browser_task_report;
#[cfg(feature = "channels")]
pub(crate) mod channel_controller;
+#[cfg(all(feature = "channels", feature = "modules"))]
+pub(crate) mod channel_runtime;
pub(crate) mod channel_health;
pub mod client;
#[cfg(feature = "modules")]