Skip to content

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

chore: files changed crates/openhuman-core/src/flows/bus/trigger.rs,crates/openhuman-core/src/flows/

Steven Enamakeld2a29b34fa3c
diff --git a/crates/openhuman-core/src/flows/bus/trigger.rs b/crates/openhuman-core/src/flows/bus/trigger.rs
index d7339d1ffd..3a14bab6c9 100644
--- a/crates/openhuman-core/src/flows/bus/trigger.rs
+++ b/crates/openhuman-core/src/flows/bus/trigger.rs
@@ -9,6 +9,8 @@ use crate::flows::store;
use async_trait::async_trait;
use serde_json::Value;
use std::collections::HashSet;
+use std::future::Future;
+use std::pin::Pin;
use std::sync::{Arc, Mutex};
use tinybus::EventHandler;
use tinyflows::model::TriggerKind;
@@ -85,16 +87,87 @@ pub struct FlowTriggerSubscriber {
/// explicitly asking to run a flow again (e.g. while a scheduled run is
/// still in flight) is fine.
in_flight: Arc<Mutex<HashSet<String>>>,
+ runner: Arc<RunExecutor>,
+ queue_capacity: usize,
}
+pub(crate) struct TriggerRunRequest {
+ pub(crate) flow_id: String,
+ pub(crate) input: Value,
+ pub(crate) inputs: serde_json::Map<String, Value>,
+ pub(crate) trigger: tinyflows_catalog::FlowRunTrigger,
+}
+
+type RunFuture = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
+type RunExecutor = dyn Fn(
+ crate::core::runtime::DispatchCtx,
+ Arc<Config>,
+ TriggerRunRequest,
+ ) -> RunFuture
+ + Send
+ + Sync;
+
+const APP_EVENT_QUEUE_CAPACITY: usize = 32;
+
impl FlowTriggerSubscriber {
pub fn new(config: Arc<Config>) -> Self {
+ Self::with_executor(config, APP_EVENT_QUEUE_CAPACITY, |ctx, config, request| async move {
+ tracing::info!(target: "flows", flow_id = %request.flow_id, "[flows] trigger fired — starting run");
+ match crate::flows::ops::flows_run(
+ &ctx,
+ &config,
+ &request.flow_id,
+ request.input,
+ request.inputs,
+ request.trigger,
+ )
+ .await
+ {
+ Ok(_) => tracing::info!(target: "flows", flow_id = %request.flow_id, "[flows] trigger-driven run finished"),
+ Err(e) => tracing::warn!(target: "flows", flow_id = %request.flow_id, error = %e, "[flows] trigger-driven run failed"),
+ }
+ })
+ }
+
+ fn with_executor<F, Fut>(config: Arc<Config>, queue_capacity: usize, runner: F) -> Self
+ where
+ F: Fn(
+ crate::core::runtime::DispatchCtx,
+ Arc<Config>,
+ TriggerRunRequest,
+ ) -> Fut
+ + Send
+ + Sync
+ + 'static,
+ Fut: Future<Output = ()> + Send + 'static,
+ {
+ let runner: Arc<RunExecutor> = Arc::new(move |ctx, config, request| {
+ Box::pin(runner(ctx, config, request))
+ });
Self {
config,
in_flight: Arc::new(Mutex::new(HashSet::new())),
+ runner,
+ queue_capacity: queue_capacity.max(1),
}
}
+ #[cfg(test)]
+ pub(crate) fn with_runner<F, Fut>(config: Arc<Config>, queue_capacity: usize, runner: F) -> Self
+ where
+ F: Fn(
+ crate::core::runtime::DispatchCtx,
+ Arc<Config>,
+ TriggerRunRequest,
+ ) -> Fut
+ + Send
+ + Sync
+ + 'static,
+ Fut: Future<Output = ()> + Send + 'static,
+ {
+ Self::with_executor(config, queue_capacity, runner)
+ }
+
/// Attempts to claim `flow_id` for a trigger-driven dispatch. Returns
/// `None` when a dispatch for the same flow is already in flight — the
/// caller should skip this tick. Returns `Some(guard)` on success; the
@@ -111,6 +184,33 @@ impl FlowTriggerSubscriber {
})
}
+ async fn dispatch_app_event(
+ &self,
+ ctx: &crate::core::runtime::DispatchCtx,
+ flow_id: String,
+ payload: Value,
+ inputs: serde_json::Map<String, Value>,
+ ) {
+ self.spawn_run(
+ ctx,
+ flow_id,
+ payload,
+ inputs,
+ tinyflows_catalog::FlowRunTrigger::AppEvent,
+ );
+ }
+
+ #[cfg(test)]
+ pub(crate) async fn dispatch_test_app_event(
+ &self,
+ ctx: &crate::core::runtime::DispatchCtx,
+ flow_id: &str,
+ payload: Value,
+ ) {
+ self.dispatch_app_event(ctx, flow_id.to_string(), payload, serde_json::Map::new())
+ .await;
+ }
+
/// The configuration to handle an event under (`super::owner::config_for_scope`).
pub(super) fn config_for_scope(&self, ctx: &crate::core::runtime::DispatchCtx) -> Arc<Config> {
super::owner::config_for_scope(ctx, &self.config)
@@ -194,13 +294,8 @@ impl FlowTriggerSubscriber {
if matches_app_event(&flow, toolkit, trigger_slug) {
matched += 1;
let inputs = pinned_trigger_inputs(&flow);
- self.spawn_run(
- &ctx,
- flow.id.clone(),
- payload.clone(),
- inputs,
- tinyflows_catalog::FlowRunTrigger::AppEvent,
- );
+ self.dispatch_app_event(&ctx, flow.id.clone(), payload.clone(), inputs)
+ .await;
}
}
tracing::debug!(target: "flows", %toolkit, %trigger_slug, matched, "[flows] app_event trigger matching complete");
@@ -229,20 +324,22 @@ impl FlowTriggerSubscriber {
let config = self.config_for_scope(ctx);
let run_ctx = ctx.clone();
+ let config = self.config_for_scope(ctx);
+ let request = TriggerRunRequest {
+ flow_id: flow_id.clone(),
+ input,
+ inputs,
+ trigger,
+ };
+ let runner = Arc::clone(&self.runner);
// Scoped: the run keeps the owner's context the handler entered.
ctx.spawn(async move {
// Held for the lifetime of the run; released on drop (including
// on panic) by `InFlightGuard`.
let _guard = guard;
- tracing::info!(target: "flows", %flow_id, "[flows] trigger fired — starting run");
- match crate::flows::ops::flows_run(&run_ctx, &config, &flow_id, input, inputs, trigger).await {
- Ok(_) => {
- tracing::info!(target: "flows", %flow_id, "[flows] trigger-driven run finished")
- }
- Err(e) => {
- tracing::warn!(target: "flows", %flow_id, error = %e, "[flows] trigger-driven run failed")
- }
- }
+ run_ctx
+ .enter((runner)(run_ctx.clone(), config, request))
+ .await;
});
}
}
diff --git a/crates/openhuman-core/src/flows/bus_subscriber_tests.rs b/crates/openhuman-core/src/flows/bus_subscriber_tests.rs
index 537266fb93..ce5ec708cc 100644
--- a/crates/openhuman-core/src/flows/bus_subscriber_tests.rs
+++ b/crates/openhuman-core/src/flows/bus_subscriber_tests.rs
@@ -209,13 +209,13 @@ async fn app_event_runs_queue_fifo_per_tenant_while_other_tenants_progress() {
let started_tx = Arc::new(Mutex::new(Some(started_tx)));
let (release_first_tx, release_first_rx) = oneshot::channel();
let release_first_rx = Arc::new(tokio::sync::Mutex::new(Some(release_first_rx)));
- let runner = Arc::new(move |ctx, flow_id, input, _inputs, _trigger| {
+ let runner = move |ctx, _config, request| {
let completed_tx = completed_tx.clone();
let started_tx = Arc::clone(&started_tx);
let release_first_rx = Arc::clone(&release_first_rx);
- Box::pin(async move {
+ async move {
let tenant = ctx.tenant().unwrap();
- let event = input["event"].as_str().unwrap().to_owned();
+ let event = request.input["event"].as_str().unwrap().to_owned();
if event == "a1" {
if let Some(started_tx) = started_tx.lock().unwrap().take() {
let _ = started_tx.send(());
@@ -225,11 +225,11 @@ async fn app_event_runs_queue_fifo_per_tenant_while_other_tenants_progress() {
}
}
completed_tx
- .send((tenant.agent.unwrap(), flow_id, event))
+ .send((tenant.agent.unwrap(), request.flow_id, event))
.unwrap();
- })
- });
- let subscriber = FlowTriggerSubscriber::with_runner(config, runner, 1);
+ }
+ };
+ let subscriber = FlowTriggerSubscriber::with_runner(config, 1, runner);
let context = |agent: &str| {
DispatchCtx::new(
CoreContext::for_test(DomainSet::full(), None).derive_with(
@@ -252,18 +252,24 @@ async fn app_event_runs_queue_fifo_per_tenant_while_other_tenants_progress() {
.dispatch_app_event(&tenant_b, "shared-flow", json!({"event": "b1"}))
.await;
+ let receive = async |rx: &mut mpsc::UnboundedReceiver<_>| {
+ tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
+ .await
+ .expect("queued trigger did not finish within the hang guard")
+ .unwrap()
+ };
assert_eq!(
- completed_rx.recv().await.unwrap(),
+ receive(&mut completed_rx).await,
("tenant-b".to_string(), "shared-flow".to_string(), "b1".to_string()),
"a held run for one tenant must not block the same flow id for another tenant"
);
release_first_tx.send(()).unwrap();
assert_eq!(
- completed_rx.recv().await.unwrap(),
+ receive(&mut completed_rx).await,
("tenant-a".to_string(), "shared-flow".to_string(), "a1".to_string())
);
assert_eq!(
- completed_rx.recv().await.unwrap(),
+ receive(&mut completed_rx).await,
("tenant-a".to_string(), "shared-flow".to_string(), "a2".to_string()),
"app_event payloads for one tenant and flow must execute FIFO"
);