Skip to main content

evorule_primitives/
io_handler.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2// Copyright (C) 2026 EvoRule Project
3// This file is part of EvoRule, licensed under GNU Affero General Public License v3 or later.
4//! I/O handler trait — object-safe, supports dynamic dispatch via trait objects.
5//!
6//! This contract was historically defined inside the reactor crate (itself
7//! moved there from governance during the H5 architecture-debt fix). It now
8//! lives at the base-primitive layer so that any ecosystem block can speak
9//! the I/O handler contract without depending on the canonical execution
10//! crates; the reactor re-exports it unchanged.
11//!
12//! # Usage example
13//!
14//! ```
15//! use async_trait::async_trait;
16//! use evorule_primitives::{IoHandler, IoResult};
17//! use evorule_primitives::JsonValue;
18//!
19//! struct EchoHandler;
20//!
21//! #[async_trait]
22//! impl IoHandler for EchoHandler {
23//!     async fn execute(&self, params: &JsonValue) -> IoResult {
24//!         Ok(params.clone())
25//!     }
26//! }
27//! ```
28
29use crate::value::JsonValue;
30use alloc::boxed::Box;
31use alloc::string::String;
32use async_trait::async_trait;
33
34/// I/O execution result.
35///
36/// On success returns a [`JsonValue`] (injected into
37/// `payload.__io_results__.{io_type}` by the reactor); on failure returns an
38/// error message (recorded into the `IoResponse.error` field).
39pub type IoResult = Result<JsonValue, String>;
40
41/// I/O handler trait — all I/O handlers implement this interface.
42///
43/// Uses `#[async_trait]` to make the trait object-safe, enabling
44/// `Arc<dyn IoHandler>` dynamic dispatch.
45///
46/// `params` comes from `Fact::IoRequest.params`, already resolved from path
47/// references into concrete values by the TCB.
48///
49/// # Implementer responsibilities
50/// - Extract the required fields from `params` (e.g. `url`, `query`, `key`)
51/// - Perform the actual I/O operation (HTTP request, SQL query, file I/O, etc.)
52/// - Return `Ok(JsonValue)` or `Err(String)`
53///
54/// # Callers
55/// - The governance `IoDispatcher` dispatches to the matching handler by `IoType`
56/// - The governance `IoSubscriber` subscribes to `Fact::IoRequest` and calls dispatch
57#[async_trait]
58pub trait IoHandler: Send + Sync {
59    /// Execute the I/O operation.
60    ///
61    /// # Parameters
62    /// - `params`: I/O request parameters (passed through by the `io_request`
63    ///   instruction; e.g. `call_external` carries
64    ///   `{"messages": [...], "tools": [...]}`, `call_service` carries
65    ///   `{"service_name": "...", "args": {...}}`)
66    ///
67    /// # Returns
68    /// - `Ok(JsonValue)`: I/O result (injected into `payload.__io_results__.{io_type}`)
69    /// - `Err(String)`: error message (recorded into `IoResponse.error`; the
70    ///   result is not consumed)
71    async fn execute(&self, params: &JsonValue) -> IoResult;
72}