Download native-api/src/lib.rs from ElderRyan/lispm-llm: direct link, hf CLI and curl.
- Browser
- Download file 6.31 kB
-
https://huggingface.co/ElderRyan/lispm-llm/resolve/main/native-api/src/lib.rs
- Command line
-
hf download hf://ElderRyan/lispm-llm/native-api/src/lib.rs
-
curl -L -o lib.rs https://huggingface.co/ElderRyan/lispm-llm/resolve/main/native-api/src/lib.rs
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. | |
| 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. | |
| pub enum ApiError { | |
| /// A malformed or unknown operation cannot enter the workflow domain. | |
| Json( serde_json::Error), | |
| /// Imported JSON or project IO failed before starting a job. | |
| Io( std::io::Error), | |
| /// The validated project workflow refused an operation. | |
| Workflow( lispm_llm::workflow::WorkflowError), | |
| /// The process-wide tensor configuration or exclusive phase is unavailable. | |
| Runtime( lispm_llm::runtime::RuntimeError), | |
| /// Paths crossing the foreign boundary must not depend on Emacs' directory. | |
| RelativePath, | |
| /// The request exceeds the documented eight-megabyte JSON limit. | |
| RequestTooLarge, | |
| /// A released or invented job handle has no observable state. | |
| UnknownJob, | |
| /// Completed jobs must be released before allocating more retained handles. | |
| JobLimit, | |
| /// Job identities never wrap or alias an earlier request. | |
| JobIdsExhausted, | |
| /// A native synchronization failure must not leave polling pending forever. | |
| StatePoisoned, | |
| /// A dependency unwind is contained inside the worker or ABI boundary. | |
| WorkerPanic, | |
| /// The caller cancelled before the operation committed its output. | |
| 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. | |
| 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. | |
| 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. | |
| 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) }); | |
| } | |
| } | |