Ryan.K
Add reusable Emacs retraining workflow and C FFI API
2109241 unverified
Raw History Blame Contribute Delete
6.31 kB
//! Stable JSON service shared by the Emacs module and a standalone C ABI.
//!
//! Long operations own background jobs. The caller polls and releases numeric
//! handles; no callback, borrowed string, or Emacs object enters a worker.
#![deny(missing_docs)]
use std::ffi::{CStr, CString, c_char};
use std::panic::{AssertUnwindSafe, catch_unwind};
use serde::Serialize;
use serde_json::{Value, json};
use thiserror::Error;
mod jobs;
mod protocol;
/// Recoverable service failures, converted into an explicit JSON error envelope.
#[derive(Debug, Error)]
pub enum ApiError {
/// A malformed or unknown operation cannot enter the workflow domain.
#[error("invalid native request: {0}")]
Json(#[from] serde_json::Error),
/// Imported JSON or project IO failed before starting a job.
#[error(transparent)]
Io(#[from] std::io::Error),
/// The validated project workflow refused an operation.
#[error(transparent)]
Workflow(#[from] lispm_llm::workflow::WorkflowError),
/// The process-wide tensor configuration or exclusive phase is unavailable.
#[error(transparent)]
Runtime(#[from] lispm_llm::runtime::RuntimeError),
/// Paths crossing the foreign boundary must not depend on Emacs' directory.
#[error("native workflow paths must be absolute local paths")]
RelativePath,
/// The request exceeds the documented eight-megabyte JSON limit.
#[error("native request is too large")]
RequestTooLarge,
/// A released or invented job handle has no observable state.
#[error("unknown or released native job")]
UnknownJob,
/// Completed jobs must be released before allocating more retained handles.
#[error("too many retained native jobs; release completed jobs first")]
JobLimit,
/// Job identities never wrap or alias an earlier request.
#[error("native job identifiers exhausted")]
JobIdsExhausted,
/// A native synchronization failure must not leave polling pending forever.
#[error("native job state is unavailable")]
StatePoisoned,
/// A dependency unwind is contained inside the worker or ABI boundary.
#[error("native operation stopped unexpectedly")]
WorkerPanic,
/// The caller cancelled before the operation committed its output.
#[error("native operation cancelled")]
Cancelled,
}
impl ApiError {
/// Stable coarse error code; detailed domain evidence stays in the message.
fn code(&self) -> &'static str {
match self {
Self::Json(_) | Self::RelativePath | Self::RequestTooLarge => "invalid_request",
Self::Io(_) => "io",
Self::Workflow(_) => "workflow",
Self::Runtime(_) => "runtime",
Self::UnknownJob => "unknown_job",
Self::JobLimit | Self::JobIdsExhausted => "job_limit",
Self::StatePoisoned | Self::WorkerPanic => "native_failure",
Self::Cancelled => "cancelled",
}
}
/// Preserve cancellation as a separate state rather than a training failure.
fn is_cancelled(&self) -> bool {
matches!(self, Self::Cancelled)
|| matches!(self, Self::Workflow(error) if error.is_cancelled())
}
/// Allocate only owned serializable error data for foreign consumers.
fn value(&self) -> Value {
json!({"code":self.code(), "message":self.to_string()})
}
}
/// Convert a domain result without leaking Rust error or handle layouts.
fn result_value<T: Serialize>(value: Result<T, ApiError>) -> Value {
match value {
Ok(result) => json!({"ok":true, "result":result}),
Err(error) => json!({"ok":false, "error":error.value()}),
}
}
/// Execute one owned UTF-8 JSON request and return a complete JSON envelope.
///
/// This is the safe entry used by the Emacs C ABI adapter. Training, benchmark
/// and finalization return immediately with a job handle. All request paths
/// are absolute. Panics from dependencies are converted into terminal errors.
pub fn request(input: &str) -> String {
let outcome = catch_unwind(AssertUnwindSafe(|| protocol::dispatch(input)));
result_value(outcome.unwrap_or(Err(ApiError::WorkerPanic))).to_string()
}
/// Return the fixed ABI major version for callers negotiating the C contract.
#[unsafe(no_mangle)]
pub extern "C" fn lispm_llm_abi_version() -> u32 {
1
}
/// Execute JSON through the C ABI and return a Rust-owned NUL-terminated string.
///
/// Null input and invalid UTF-8 produce an error envelope. The response must
/// be released exactly once with `lispm_llm_string_free`, never libc `free`.
///
/// # Safety
/// A non-null `input` must point to a valid NUL-terminated string whose storage
/// remains readable until this function returns. No input pointer is retained.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn lispm_llm_request(input: *const c_char) -> *mut c_char {
let response = catch_unwind(AssertUnwindSafe(|| {
if input.is_null() {
return json!({"ok":false,"error":{"code":"invalid_request","message":"null JSON request"}}).to_string();
}
// SAFETY: the caller guarantees readable NUL-terminated storage; it is
// borrowed only here and copied by the JSON decoder before any worker.
match unsafe { CStr::from_ptr(input) }.to_str() {
Ok(input) => request(input),
Err(_) => json!({"ok":false,"error":{"code":"invalid_request","message":"request must be UTF-8"}}).to_string(),
}
}));
let encoded =
response.unwrap_or_else(|_| result_value::<Value>(Err(ApiError::WorkerPanic)).to_string());
match CString::new(encoded) {
Ok(value) => value.into_raw(),
Err(_) => c"{\"ok\":false,\"error\":{\"code\":\"native_failure\",\"message\":\"invalid response string\"}}".to_owned().into_raw(),
}
}
/// Release one response allocated by `lispm_llm_request`; null is a no-op.
///
/// # Safety
/// A non-null pointer must be an unmodified, live response from this same
/// library instance. It must not have been freed before or be used afterward.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn lispm_llm_string_free(value: *mut c_char) {
if !value.is_null() {
// SAFETY: the caller returns exactly the allocation owned by this ABI.
drop(unsafe { CString::from_raw(value) });
}
}