Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

6.9 KB
Raw Blame
use crate::{
    component::{PyComponentMountHandle, PyComponentProcessor},
    context::{PyComponentProcessorContext, PyFnCallContext},
    prelude::*,
    runtime::build_on_error,
    stable_path::{PyStableKey, PyStablePath},
};

use cocoindex_core::engine::component::RunCompleteness;
use cocoindex_core::engine::live_component::LiveComponentController;
use cocoindex_py_utils::from_py_future;
use pyo3_async_runtimes::tokio::future_into_py;

#[pyclass(name = "LiveComponentController", skip_from_py_object)]
#[derive(Clone)]
pub struct PyLiveComponentController(pub Arc<LiveComponentController<PyEngineProfile>>);

#[pymethods]
impl PyLiveComponentController {
    pub fn skips_subpath(&self, stable_path: PyStablePath) -> bool {
        self.0.skips_subpath(&stable_path.0)
    }

    pub fn update_full_async<'py>(
        &self,
        py: Python<'py>,
        processor: PyComponentProcessor,
        handler_callback: Option<Py<PyAny>>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let ctrl = self.0.clone();
        let host_runtime_ctx = ctrl.component().app_ctx().env().host_runtime_ctx().clone();
        let on_error = build_on_error(host_runtime_ctx, handler_callback);
        future_into_py(py, async move {
            let completeness = ctrl
                .update_full(processor, on_error)
                .await
                .into_py_result()?;
            Ok(completeness == RunCompleteness::Complete)
        })
    }

    pub fn update_async<'py>(
        &self,
        py: Python<'py>,
        stable_path: PyStablePath,
        processor: PyComponentProcessor,
        handler_callback: Option<Py<PyAny>>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let ctrl = self.0.clone();
        let host_runtime_ctx = ctrl.component().app_ctx().env().host_runtime_ctx().clone();
        let on_error = build_on_error(host_runtime_ctx, handler_callback);
        future_into_py(py, async move {
            let handle = ctrl
                .update(stable_path.0, processor, on_error)
                .await
                .into_py_result()?;
            Ok(PyComponentMountHandle::from_handle(handle))
        })
    }

    pub fn delete_async<'py>(
        &self,
        py: Python<'py>,
        stable_path: PyStablePath,
        handler_callback: Option<Py<PyAny>>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let ctrl = self.0.clone();
        let host_runtime_ctx = ctrl.component().app_ctx().env().host_runtime_ctx().clone();
        let on_error = build_on_error(host_runtime_ctx, handler_callback);
        future_into_py(py, async move {
            let handle = ctrl
                .delete(stable_path.0, on_error)
                .await
                .into_py_result()?;
            Ok(PyComponentMountHandle::from_handle(handle))
        })
    }

    pub fn mark_ready_async<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        let ctrl = self.0.clone();
        future_into_py(py, async move {
            ctrl.mark_ready().await;
            Ok(())
        })
    }

    pub fn start(&self, py: Python<'_>, process_live_fut: Py<PyAny>) -> PyResult<()> {
        // Convert the Python coroutine into a Rust future using from_py_future.
        let host_runtime_ctx = self.0.component().app_ctx().env().host_runtime_ctx();
        let fut = from_py_future(py, &host_runtime_ctx.0, process_live_fut.into_bound(py))?;
        // Wrap to convert PyResult<Py<PyAny>> β†’ Result<()>
        let rust_fut = async move {
            fut.await.from_py_result()?;
            Ok(())
        };
        self.0.start(rust_fut);
        Ok(())
    }

    /// Mount a nested live component at `stable_path` from inside this
    /// controller's `process_live` (Slice F: `operator.update(LiveCompClass)`
    /// branch). Returns `(inner_controller, readiness_handle)` β€” caller
    /// constructs a Python `LiveComponentOperator` for the inner instance,
    /// then calls `inner_controller.start(instance.process_live(operator))`.
    /// Returns `None` when the update's selector leaves the child out.
    pub fn mount_inner_live_async<'py>(
        &self,
        py: Python<'py>,
        stable_path: PyStablePath,
    ) -> PyResult<Bound<'py, PyAny>> {
        let ctrl = self.0.clone();
        future_into_py(py, async move {
            let result = ctrl
                .mount_inner_live(stable_path.0)
                .await
                .into_py_result()?;
            Ok(result.map(|result| {
                let py_controller = PyLiveComponentController(Arc::new(result.controller));
                let py_handle = PyComponentMountHandle::from_handle(result.readiness_handle);
                (py_controller, py_handle)
            }))
        })
    }

    #[getter]
    pub fn is_live(&self) -> bool {
        self.0.is_live()
    }

    /// Read previously-committed user state for `key` (written via
    /// `coco.use_state` inside `process()`), as a fresh standalone read.
    /// Returns `None` if absent. Callable from `process_live` to gate a
    /// durable startup-scan skip.
    pub fn read_committed_state_async<'py>(
        &self,
        py: Python<'py>,
        key: PyStableKey,
    ) -> PyResult<Bound<'py, PyAny>> {
        let ctrl = self.0.clone();
        future_into_py(py, async move {
            let value = ctrl.read_committed_state(&key.0).await.into_py_result()?;
            Ok(value)
        })
    }

    /// Commit `value` under `key` in this live component's persistent user
    /// state (the `Live` keyspace), read back by `read_committed_state` on a
    /// later run. Counterpart writer to `read_committed_state_async`; the
    /// value is pre-serialized opaque bytes.
    pub fn write_committed_state_async<'py>(
        &self,
        py: Python<'py>,
        key: PyStableKey,
        value: Vec<u8>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let ctrl = self.0.clone();
        future_into_py(py, async move {
            ctrl.write_committed_state(&key.0, value)
                .await
                .into_py_result()?;
            Ok(())
        })
    }
}

#[pyfunction]
pub fn mount_live_async<'py>(
    py: Python<'py>,
    stable_path: PyStablePath,
    comp_ctx: PyComponentProcessorContext,
    fn_ctx: &PyFnCallContext,
    live: bool,
) -> PyResult<Bound<'py, PyAny>> {
    // Sync phase: borrows fn_ctx (only valid for this call).
    let pending = cocoindex_core::engine::live_component::mount_live_prepare(
        &comp_ctx.0,
        &fn_ctx.0,
        stable_path.0,
        live,
    )
    .into_py_result()?;

    // Async phase: no borrows needed, all data is owned.
    future_into_py(py, async move {
        // `None`: the update's selector leaves the component out.
        let Some(pending) = pending else {
            return Ok(None);
        };
        let result = pending.complete().await.into_py_result()?;
        let py_controller = PyLiveComponentController(Arc::new(result.controller));
        let py_handle = PyComponentMountHandle::from_handle(result.readiness_handle);
        Ok(Some((py_controller, py_handle)))
    })
}