evorule-plugin-kit 0.2.0

In-process native plugin mechanism common crate: NativeService trait, service declaration entries, and a generic filter router shared by all evorule-services plugin families
Documentation
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2026 EvoRule Project
// This file is part of EvoRule, licensed under GNU Affero General Public License v3 or later.
//! Mechanism gateway: the single injection point for canonical mechanism
//! execution (meta-instruction evaluation) into plugin families.
//!
//! The plugin-kit crate deliberately carries **no** dependency on the
//! canonical repo (`evorule-tcb` / `evorule-reactor`). Mechanism-dependent
//! services (e.g. the inference family's forward simulation) obtain their
//! meta-instruction executor exclusively through this gateway, which the
//! host process registers at startup:
//!
//! - **Hosts** (the canonical consumer of the mechanism layer, e.g.
//!   `evorule-server`) implement [`MechanismGateway`] and call
//!   [`register_mechanism_gateway`] during plugin loading. This keeps the
//!   service entry point (`evorule-server`) as the only legitimate consumer
//!   of canonical mechanism capabilities.
//! - **Guests** (wasm32 family modules) ship **without** a gateway: their
//!   compile graph contains no canonical crates at all, and any
//!   mechanism-dependent call fails visibly with
//!   [`GATEWAY_UNAVAILABLE_ERR`] (never a silent fallback, never a stub
//!   impersonating the real mechanism).
//!
//! # Failure semantics (fail-visible)
//!
//! [`require_mechanism_gateway`] returns a self-describing error when no
//! gateway has been registered. Callers surface this error through their
//! regular business-error channel; nothing degrades silently.
//!
//! # Result mirroring
//!
//! [`MetaOutcome`] mirrors the canonical executor's result enum arm-for-arm
//! (state / io-required / halted). The host-side implementation performs a
//! mechanical three-arm mapping; no semantic reinterpretation happens on
//! either side of the boundary.

#![forbid(unsafe_code)]

use std::sync::{Arc, OnceLock};

use crate::reexports::JsonValue;

/// Canonical fail-visible error for mechanism calls without a registered
/// gateway. Byte-stable by design: host-side and guest-side runs must
/// produce the identical error text so downstream golden vectors and
/// parity comparisons stay deterministic.
pub const GATEWAY_UNAVAILABLE_ERR: &str = "mechanism gateway not available in this runtime \
     (guest runtimes ship without a mechanism gateway by design; hosts must register one via \
     register_mechanism_gateway at startup)";

/// Outcome of one meta-instruction execution, mirrored arm-for-arm from the
/// canonical executor's result type (state / io-required / halted).
///
/// This mirror lives in plugin-kit (not in the primitive-types layer) on
/// purpose: it carries mechanism semantics, which must not leak into the
/// base value-domain crate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MetaOutcome {
    /// Execution produced an updated state document.
    State(JsonValue),
    /// I/O request signal (propagates immediately; no further instructions
    /// execute within the step).
    IoRequired {
        /// I/O type (e.g. `call_external`, `query_db`).
        io_type: String,
        /// I/O request parameters (path references already resolved to
        /// concrete values).
        params: JsonValue,
    },
    /// Enforce-primitive hit: pure halt signal, no state attached; any
    /// state modification made before the hit is discarded by the
    /// canonical transition layer.
    Halted {
        /// Violation description (enforce `params.reason`, echoed for
        /// violation-fact audit).
        reason: String,
    },
}

/// Host-side mechanism executor: synchronous pure-function view over the
/// canonical meta-instruction state machine.
pub trait MechanismGateway: Send + Sync {
    /// Execute one meta instruction against `state` at nesting `depth`,
    /// returning the mirrored outcome. Errors are plain strings (the host
    /// implementation flattens the canonical error type via `Display`).
    ///
    /// # Errors
    ///
    /// Budget exhaustion, depth overrun, or an invalid instruction tree —
    /// passed through verbatim from the canonical executor.
    fn execute_meta_instruction(
        &self,
        instr: &JsonValue,
        state: JsonValue,
        depth: usize,
    ) -> Result<MetaOutcome, String>;
}

static GATEWAY: OnceLock<Arc<dyn MechanismGateway>> = OnceLock::new();

/// Register the process-wide mechanism gateway (host startup / plugin
/// loading path).
///
/// # Errors
///
/// A gateway is already registered — fail-fast, no silent replacement (the
/// first registration wins for the lifetime of the process).
pub fn register_mechanism_gateway(gateway: Arc<dyn MechanismGateway>) -> Result<(), String> {
    GATEWAY.set(gateway).map_err(|_| {
        "a mechanism gateway is already registered - fail-fast, no silent replacement \
         (register_mechanism_gateway must be called exactly once per process)"
            .to_string()
    })
}

/// Registered gateway, if any. Hosts register at startup; guests never do.
pub fn mechanism_gateway() -> Option<&'static Arc<dyn MechanismGateway>> {
    GATEWAY.get()
}

/// Fail-visible accessor: the registered gateway or
/// [`GATEWAY_UNAVAILABLE_ERR`]. Mechanism-dependent services must go through
/// this accessor (never silently degrade when [`mechanism_gateway`] is
/// `None`).
///
/// # Errors
///
/// No gateway registered in this runtime (guest case, or a host that missed
/// its startup registration).
pub fn require_mechanism_gateway() -> Result<&'static Arc<dyn MechanismGateway>, String> {
    GATEWAY
        .get()
        .ok_or_else(|| GATEWAY_UNAVAILABLE_ERR.to_string())
}