Skip to content

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

style: format channel runtime and delivery code

Steven Enamakel2d7822b4eb9a
diff --git a/crates/openhuman-core/src/channels/bus/delivery.rs b/crates/openhuman-core/src/channels/bus/delivery.rs
index 3ad86c68fd..52b252a02c 100644
--- a/crates/openhuman-core/src/channels/bus/delivery.rs
+++ b/crates/openhuman-core/src/channels/bus/delivery.rs
@@ -1,15 +1,25 @@
//! Captured managed transport for module-owned progressive replies.
use crate::backend::{BackendApiError, BackendClient};
-use crate::security::credentials::session_support::{get_session_token, is_local_session_token, BackendCredential};
-use crate::modules::{channel_runtime::ChannelRuntimeLease, client::{ModuleClient, ModuleCallError}};
-use tinychannels_bus::{ChannelBackendRequest, ChannelBackendResult, methods};
-use tinychannels_bus::module_progressive::{ProgressiveCommand, ProgressiveEvent, ProgressiveResult, ProgressiveTransportRequest, ProgressiveTransportResult};
+use crate::modules::{
+ channel_runtime::ChannelRuntimeLease,
+ client::{ModuleCallError, ModuleClient},
+};
+use crate::security::credentials::session_support::{
+ get_session_token, is_local_session_token, BackendCredential,
+};
use serde_json::{json, Value};
+use tinychannels_bus::module_progressive::{
+ ProgressiveCommand, ProgressiveEvent, ProgressiveResult, ProgressiveTransportRequest,
+ ProgressiveTransportResult,
+};
+use tinychannels_bus::{methods, ChannelBackendRequest, ChannelBackendResult};
/// Transport refusals are typed facts; recovery and retry budgets belong to the module.
pub(super) fn map_backend_error(error: anyhow::Error) -> ProgressiveTransportResult {
match error.downcast_ref::<BackendApiError>() {
- Some(BackendApiError::ChannelEditUnsupported { .. }) => ProgressiveTransportResult::EditUnsupported,
+ Some(BackendApiError::ChannelEditUnsupported { .. }) => {
+ ProgressiveTransportResult::EditUnsupported
+ }
Some(BackendApiError::MessageNotFound { .. }) => ProgressiveTransportResult::MessageGone,
_ => ProgressiveTransportResult::Failed,
}
@@ -27,27 +37,66 @@ impl ManagedTransport {
Some(token) if !is_local_session_token(&token) => BackendCredential::Session(token),
_ => anyhow::bail!("Hosted channel credential unavailable"),
};
- Ok(Self { client: BackendClient::from_config(config)?, credential })
+ Ok(Self {
+ client: BackendClient::from_config(config)?,
+ credential,
+ })
}
async fn execute(&self, request: ProgressiveTransportRequest) -> ProgressiveTransportResult {
let result = match request {
- ProgressiveTransportRequest::Send { channel, message } => self.client.send_channel_message(&channel, &self.credential, message).await,
- ProgressiveTransportRequest::Edit { channel, message_id, text } => self.client.send_channel_edit(&channel, &message_id, &self.credential, json!({"text":text})).await,
- ProgressiveTransportRequest::Delete { channel, message_id } => self.client.send_channel_delete(&channel, &message_id, &self.credential).await,
- ProgressiveTransportRequest::Typing { channel } => self.client.send_channel_typing(&channel, &self.credential).await,
+ ProgressiveTransportRequest::Send { channel, message } => {
+ self.client
+ .send_channel_message(&channel, &self.credential, message)
+ .await
+ }
+ ProgressiveTransportRequest::Edit {
+ channel,
+ message_id,
+ text,
+ } => {
+ self.client
+ .send_channel_edit(
+ &channel,
+ &message_id,
+ &self.credential,
+ json!({"text":text}),
+ )
+ .await
+ }
+ ProgressiveTransportRequest::Delete {
+ channel,
+ message_id,
+ } => {
+ self.client
+ .send_channel_delete(&channel, &message_id, &self.credential)
+ .await
+ }
+ ProgressiveTransportRequest::Typing { channel } => {
+ self.client
+ .send_channel_typing(&channel, &self.credential)
+ .await
+ }
};
- match result { Ok(value) => ProgressiveTransportResult::Success(value), Err(error) => map_backend_error(error) }
+ match result {
+ Ok(value) => ProgressiveTransportResult::Success(value),
+ Err(error) => map_backend_error(error),
+ }
}
}
#[tinybus::interface(name = "ai.tinyhumans.tinychannels.ChannelsHost")]
impl ManagedTransport {
- async fn dispatch_controller_backend(&self, request: ChannelBackendRequest) -> tinybus::Result<ChannelBackendResult> {
+ async fn dispatch_controller_backend(
+ &self,
+ request: ChannelBackendRequest,
+ ) -> tinybus::Result<ChannelBackendResult> {
let ChannelBackendRequest::ProgressiveTransport(request) = request else {
return Err(tinybus::Error::failed("callback capability unavailable"));
};
- Ok(ChannelBackendResult::ProgressiveTransport(self.execute(request).await))
+ Ok(ChannelBackendResult::ProgressiveTransport(
+ self.execute(request).await,
+ ))
}
}
@@ -58,25 +107,65 @@ pub(super) struct ModuleProgressiveReply {
}
impl ModuleProgressiveReply {
- pub(super) async fn open(config: crate::config::Config, channel: String) -> anyhow::Result<Self> {
+ pub(super) async fn open(
+ config: crate::config::Config,
+ channel: String,
+ ) -> anyhow::Result<Self> {
let callback = ManagedTransport::capture(&config)?;
let runtime = ChannelRuntimeLease::open(ModuleClient::new(config), callback).await?;
- let result: ProgressiveResult = runtime.object().call_confidential(methods::EXECUTE_PROGRESSIVE, (ProgressiveCommand::Open { channel },)).await?;
+ let result: ProgressiveResult = runtime
+ .object()
+ .call_confidential(
+ methods::EXECUTE_PROGRESSIVE,
+ (ProgressiveCommand::Open { channel },),
+ )
+ .await?;
match result {
- ProgressiveResult::Opened { handle } if !handle.is_empty() && handle.len() <= 128 => Ok(Self { runtime, handle }),
- _ => { ModuleClient::report_malformed_reply("tinychannels"); Err(ModuleCallError::ModuleFault.into()) }
+ ProgressiveResult::Opened { handle } if !handle.is_empty() && handle.len() <= 128 => {
+ Ok(Self { runtime, handle })
+ }
+ _ => {
+ ModuleClient::report_malformed_reply("tinychannels");
+ Err(ModuleCallError::ModuleFault.into())
+ }
}
}
pub(super) async fn feed(&self, events: Vec<ProgressiveEvent>) -> Result<(), ModuleCallError> {
- let result: ProgressiveResult = self.runtime.object().call_confidential(methods::EXECUTE_PROGRESSIVE, (ProgressiveCommand::Feed { handle: self.handle.clone(), events },)).await?;
- if result != ProgressiveResult::Updated { ModuleClient::report_malformed_reply("tinychannels"); return Err(ModuleCallError::ModuleFault); }
+ let result: ProgressiveResult = self
+ .runtime
+ .object()
+ .call_confidential(
+ methods::EXECUTE_PROGRESSIVE,
+ (ProgressiveCommand::Feed {
+ handle: self.handle.clone(),
+ events,
+ },),
+ )
+ .await?;
+ if result != ProgressiveResult::Updated {
+ ModuleClient::report_malformed_reply("tinychannels");
+ return Err(ModuleCallError::ModuleFault);
+ }
Ok(())
}
pub(super) async fn finalize(&self, text: &str) -> Result<(), ModuleCallError> {
- let result: ProgressiveResult = self.runtime.object().call_confidential(methods::EXECUTE_PROGRESSIVE, (ProgressiveCommand::Finish { handle: self.handle.clone(), text: text.into() },)).await?;
- if result != ProgressiveResult::Closed { ModuleClient::report_malformed_reply("tinychannels"); return Err(ModuleCallError::ModuleFault); }
+ let result: ProgressiveResult = self
+ .runtime
+ .object()
+ .call_confidential(
+ methods::EXECUTE_PROGRESSIVE,
+ (ProgressiveCommand::Finish {
+ handle: self.handle.clone(),
+ text: text.into(),
+ },),
+ )
+ .await?;
+ if result != ProgressiveResult::Closed {
+ ModuleClient::report_malformed_reply("tinychannels");
+ return Err(ModuleCallError::ModuleFault);
+ }
self.runtime.close().await
}
}
diff --git a/crates/openhuman-core/src/channels/bus/subscriber.rs b/crates/openhuman-core/src/channels/bus/subscriber.rs
index ead0fd3057..71a436dabe 100644
--- a/crates/openhuman-core/src/channels/bus/subscriber.rs
+++ b/crates/openhuman-core/src/channels/bus/subscriber.rs
@@ -127,7 +127,9 @@ impl EventHandler<DomainEvent> for ChannelInboundSubscriber {
}
Err(err) => {
tracing::error!("[channel-inbound] start_chat failed: {}", err);
- let _ = reply.finalize(&format!("Sorry, I couldn't process your message: {err}")).await;
+ let _ = reply
+ .finalize(&format!("Sorry, I couldn't process your message: {err}"))
+ .await;
return;
}
};
diff --git a/crates/openhuman-core/src/modules/channel_runtime.rs b/crates/openhuman-core/src/modules/channel_runtime.rs
index 90dbd0e579..5920c511dc 100644
--- a/crates/openhuman-core/src/modules/channel_runtime.rs
+++ b/crates/openhuman-core/src/modules/channel_runtime.rs
@@ -1,11 +1,16 @@
//! Identity-scoped channel objects and cancellation-safe callback ownership.
-use std::sync::{atomic::{AtomicBool, Ordering}, Arc};
+use super::client::{ModuleCallError, ModuleClient, ModuleObjectClient};
+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};
+use tinychannels_bus::{
+ methods, ChannelRuntimeReservation, HOST_BUS_NAME, HOST_OBJECT_PATH, OBJECT_PATH,
+};
+use tokio::sync::Mutex;
const CLOSE_BUDGET: Duration = Duration::from_secs(15);
@@ -37,8 +42,10 @@ impl Cleanup {
}
// 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;
+ 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) {
@@ -85,9 +92,12 @@ impl ChannelRuntimeLease {
) -> Result<Self, ModuleCallError> {
// This check performs lazy admission before starting any callback work.
let reservation: ChannelRuntimeReservation = client
- .call_confidential("tinychannels", methods::RESERVE_RUNTIME, ()).await?;
+ .call_confidential("tinychannels", methods::RESERVE_RUNTIME, ())
+ .await?;
validate_reservation(&reservation)?;
- let runtime = super::host::runtime().await.map_err(|_| ModuleCallError::TransportFailed)?;
+ 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;
@@ -95,7 +105,9 @@ impl ChannelRuntimeLease {
// activation task itself is independent of the requesting runtime.
let _ = sender.send(result);
});
- receiver.await.map_err(|_| ModuleCallError::TransportFailed)?
+ receiver
+ .await
+ .map_err(|_| ModuleCallError::TransportFailed)?
}
async fn activate(
@@ -107,42 +119,73 @@ impl ChannelRuntimeLease {
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)
+ 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)),
+ 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 {
+ 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;
- }});
+ 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?;
+ 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) 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(()); }
+ 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)?;
+ .await
+ .map_err(|_| ModuleCallError::TransportFailed)?;
closing.take();
result.map_err(|_| ModuleCallError::TransportFailed)?
}
@@ -150,9 +193,13 @@ impl ChannelRuntimeLease {
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
+ .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)
+ || reservation.host_object_path
+ != format!("{HOST_OBJECT_PATH}/runtime_{}", reservation.handle)
{
ModuleClient::report_malformed_reply("tinychannels");
return Err(ModuleCallError::ModuleFault);
diff --git a/crates/openhuman-core/src/modules/channel_runtime_tests.rs b/crates/openhuman-core/src/modules/channel_runtime_tests.rs
index df879f9a29..6a02ef2a3b 100644
--- a/crates/openhuman-core/src/modules/channel_runtime_tests.rs
+++ b/crates/openhuman-core/src/modules/channel_runtime_tests.rs
@@ -12,18 +12,38 @@ fn reservation() -> ChannelRuntimeReservation {
#[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));
+ 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));
+ 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));
+ 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 33705cba7c..a111c96a5c 100644
--- a/crates/openhuman-core/src/modules/client.rs
+++ b/crates/openhuman-core/src/modules/client.rs
@@ -149,12 +149,17 @@ impl ModuleClient {
}
#[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));
+ 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)
diff --git a/crates/openhuman-core/src/modules/mod.rs b/crates/openhuman-core/src/modules/mod.rs
index daf23198d6..c3aa321f7b 100644
--- a/crates/openhuman-core/src/modules/mod.rs
+++ b/crates/openhuman-core/src/modules/mod.rs
@@ -51,9 +51,9 @@ pub mod browser_task;
mod browser_task_report;
#[cfg(feature = "channels")]
pub(crate) mod channel_controller;
+pub(crate) mod channel_health;
#[cfg(all(feature = "channels", feature = "modules"))]
pub(crate) mod channel_runtime;
-pub(crate) mod channel_health;
pub mod client;
#[cfg(feature = "modules")]
pub mod computer;