Lines
96.77 %
Functions
100 %
Branches
use nomiscript::{Expr, Number, Value, format_value};
use thiserror::Error;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RequestId {
Int(i64),
String(String),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Request {
pub id: RequestId,
pub form: Expr,
/// Wire-level error code. Every code is a Lisp-style symbol string,
/// rendered as the bare token after `:code` in the response envelope.
/// The wire surface is open: well-known engine-emitted codes are
/// associated `&str` constants on the type, while script-raised codes
/// (via `(error 'symbol "msg")`) flow through the same channel without
/// a sentinel. Clients pattern-match identically on engine and script
/// codes — adding a new well-known code is a non-breaking change.
pub struct ErrorCode(String);
impl ErrorCode {
pub fn new(symbol: impl Into<String>) -> Self {
Self(symbol.into())
#[must_use]
pub fn as_symbol(&self) -> &str {
&self.0
pub const ARGS: &str = "args";
pub const CONFIG: &str = "config";
pub const DB: &str = "db";
pub const SERVER: &str = "server";
pub const FINANCE: &str = "finance";
pub const SCRIPT: &str = "script";
pub const PARSE: &str = "parse";
pub const COMPILE: &str = "compile";
pub const RUNTIME: &str = "runtime";
pub const AUTH: &str = "auth";
pub const INTERRUPTED: &str = "interrupted";
pub const FORM_INVALID: &str = "form-invalid";
/// A write met a concurrent one on every attempt, or a stream's queue was full;
/// running it again may succeed.
pub const BUSY: &str = "busy";
/// A request would open a stream past the connection's cap.
pub const TOO_MANY_STREAMS: &str = "too-many-streams";
/// `convert-commodity` found no Price row linking source and
/// target in either direction. A host-classification label (not a
/// raised condition): `cmd_failure` turns the missing price of
/// `convert-commodity` into this host condition, and the remedy differs from a commodity
/// mismatch (add a price row vs. avoid the cross-commodity arithmetic).
///
/// Note: `commodity-mismatch` is NOT a const here — unlike `no-conversion`
/// it is a *raised condition* (the guest `throw`s `$nomi_error` with the
/// reader-folded symbol code `COMMODITY-MISMATCH`; ADR-0026), so it rides
/// the `ScriptRaised` path with its code verbatim, like any script
/// `(error 'sym …)`. It needs no well-known const.
pub const NO_CONVERSION: &str = "no-conversion";
/// The entity a command names does not exist (or is not visible to the user).
pub const NOT_FOUND: &str = "not-found";
/// The database cannot be reached right now (pool exhausted or timed out, tenant
/// quarantined, disabled or unknown); running it again later may succeed.
pub const UNAVAILABLE: &str = "unavailable";
/// The codes a native can throw as a host condition.
pub const HOST_CONDITIONS: [&str; 6] = [
Self::ARGS,
Self::BUSY,
Self::FORM_INVALID,
Self::NO_CONVERSION,
Self::NOT_FOUND,
Self::UNAVAILABLE,
];
pub enum ResponsePayload {
Value(Value),
Error {
code: ErrorCode,
message: String,
detail: Option<Value>,
},
pub struct Response {
/// Written only when non-zero.
pub stream: u32,
pub payload: ResponsePayload,
#[derive(Debug, Error)]
pub enum EnvelopeError {
#[error("frame parse error: {0}")]
Parse(String),
#[error("envelope must contain exactly one top-level expression")]
NotSingleExpr,
#[error("envelope must be a list of plist pairs")]
NotPlist,
#[error("missing required key {0}")]
MissingKey(&'static str),
#[error("invalid value for key {0}: {1}")]
InvalidValue(&'static str, String),
InvalidStream(&'static str, String),
#[error("control frames need a multiplexed connection")]
Unsupported,
mod frame;
pub use frame::{Frame, read_frame};
pub fn format_response(response: &Response) -> String {
let id = format_id(&response.id);
let head = match response.stream {
0 => id,
stream => format!("{id} :stream {stream}"),
};
match &response.payload {
ResponsePayload::Value(value) => format!("(:id {head} :value {})", format_value(value)),
ResponsePayload::Error {
code,
message,
detail,
} => {
let detail = detail
.as_ref()
.map(|detail| format!(" :detail {}", format_value(detail)))
.unwrap_or_default();
format!(
"(:id {head} :error (:code {} :message {}{detail}))",
code.as_symbol(),
format_value(&Value::String(message.clone()))
)
/// The response `frame` with `:notices` added when there are any.
pub fn with_notices(frame: String, notices: &[String]) -> String {
match frame.strip_suffix(')') {
Some(head) if !notices.is_empty() => {
let items: Vec<String> = notices
.iter()
.map(|notice| format_value(&Value::String(notice.clone())))
.collect();
format!("{head} :notices ({}))", items.join(" "))
_ => frame,
fn format_id(id: &RequestId) -> String {
match id {
RequestId::Int(n) => n.to_string(),
RequestId::String(s) => format_value(&Value::String(s.clone())),
pub(crate) fn collect_plist(items: Vec<Expr>) -> Result<Vec<(String, Expr)>, EnvelopeError> {
if !items.len().is_multiple_of(2) {
return Err(EnvelopeError::NotPlist);
let mut pairs = Vec::with_capacity(items.len() / 2);
let mut iter = items.into_iter();
while let Some(key) = iter.next() {
let key_name = match key {
Expr::Keyword(name) => name,
_ => return Err(EnvelopeError::NotPlist),
let value = iter.next().ok_or(EnvelopeError::NotPlist)?;
pairs.push((key_name, value));
Ok(pairs)
pub(crate) fn expr_to_request_id(expr: &Expr) -> Result<RequestId, EnvelopeError> {
match expr {
Expr::Number(Number::Index(id)) => Ok(RequestId::Int(*id)),
Expr::Number(n @ Number::Scalar(_)) => Err(EnvelopeError::InvalidValue(
":id",
format!("expected integer, got {n}"),
)),
Expr::String(s) => Ok(RequestId::String(s.clone())),
other => Err(EnvelopeError::InvalidValue(
format!("expected integer or string, got {other:?}"),
#[cfg(test)]
mod tests;