Skip to main content

rpc/
envelope.rs

1use nomiscript::{Expr, Number, Value, format_value};
2use thiserror::Error;
3
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub enum RequestId {
6    Int(i64),
7    String(String),
8}
9
10#[derive(Debug, Clone, PartialEq)]
11pub struct Request {
12    pub id: RequestId,
13    pub form: Expr,
14}
15
16/// Wire-level error code. Every code is a Lisp-style symbol string,
17/// rendered as the bare token after `:code` in the response envelope.
18/// The wire surface is open: well-known engine-emitted codes are
19/// associated `&str` constants on the type, while script-raised codes
20/// (via `(error 'symbol "msg")`) flow through the same channel without
21/// a sentinel. Clients pattern-match identically on engine and script
22/// codes — adding a new well-known code is a non-breaking change.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct ErrorCode(String);
25
26impl ErrorCode {
27    pub fn new(symbol: impl Into<String>) -> Self {
28        Self(symbol.into())
29    }
30
31    #[must_use]
32    pub fn as_symbol(&self) -> &str {
33        &self.0
34    }
35
36    pub const ARGS: &str = "args";
37    pub const CONFIG: &str = "config";
38    pub const DB: &str = "db";
39    pub const SERVER: &str = "server";
40    pub const FINANCE: &str = "finance";
41    pub const SCRIPT: &str = "script";
42    pub const PARSE: &str = "parse";
43    pub const COMPILE: &str = "compile";
44    pub const RUNTIME: &str = "runtime";
45    pub const AUTH: &str = "auth";
46    pub const INTERRUPTED: &str = "interrupted";
47    pub const FORM_INVALID: &str = "form-invalid";
48    /// A write met a concurrent one on every attempt, or a stream's queue was full;
49    /// running it again may succeed.
50    pub const BUSY: &str = "busy";
51    /// A request would open a stream past the connection's cap.
52    pub const TOO_MANY_STREAMS: &str = "too-many-streams";
53    /// `convert-commodity` found no Price row linking source and
54    /// target in either direction. A host-classification label (not a
55    /// raised condition): `cmd_failure` turns the missing price of
56    /// `convert-commodity` into this host condition, and the remedy differs from a commodity
57    /// mismatch (add a price row vs. avoid the cross-commodity arithmetic).
58    ///
59    /// Note: `commodity-mismatch` is NOT a const here — unlike `no-conversion`
60    /// it is a *raised condition* (the guest `throw`s `$nomi_error` with the
61    /// reader-folded symbol code `COMMODITY-MISMATCH`; ADR-0026), so it rides
62    /// the `ScriptRaised` path with its code verbatim, like any script
63    /// `(error 'sym …)`. It needs no well-known const.
64    pub const NO_CONVERSION: &str = "no-conversion";
65    /// The entity a command names does not exist (or is not visible to the user).
66    pub const NOT_FOUND: &str = "not-found";
67    /// The database cannot be reached right now (pool exhausted or timed out, tenant
68    /// quarantined, disabled or unknown); running it again later may succeed.
69    pub const UNAVAILABLE: &str = "unavailable";
70
71    /// The codes a native can throw as a host condition.
72    pub const HOST_CONDITIONS: [&str; 6] = [
73        Self::ARGS,
74        Self::BUSY,
75        Self::FORM_INVALID,
76        Self::NO_CONVERSION,
77        Self::NOT_FOUND,
78        Self::UNAVAILABLE,
79    ];
80}
81
82#[derive(Debug, Clone, PartialEq)]
83pub enum ResponsePayload {
84    Value(Value),
85    Error {
86        code: ErrorCode,
87        message: String,
88        detail: Option<Value>,
89    },
90}
91
92#[derive(Debug, Clone, PartialEq)]
93pub struct Response {
94    pub id: RequestId,
95    /// Written only when non-zero.
96    pub stream: u32,
97    pub payload: ResponsePayload,
98}
99
100#[derive(Debug, Error)]
101pub enum EnvelopeError {
102    #[error("frame parse error: {0}")]
103    Parse(String),
104    #[error("envelope must contain exactly one top-level expression")]
105    NotSingleExpr,
106    #[error("envelope must be a list of plist pairs")]
107    NotPlist,
108    #[error("missing required key {0}")]
109    MissingKey(&'static str),
110    #[error("invalid value for key {0}: {1}")]
111    InvalidValue(&'static str, String),
112    #[error("invalid value for key {0}: {1}")]
113    InvalidStream(&'static str, String),
114    #[error("control frames need a multiplexed connection")]
115    Unsupported,
116}
117
118mod frame;
119pub use frame::{Frame, read_frame};
120
121pub fn format_response(response: &Response) -> String {
122    let id = format_id(&response.id);
123    let head = match response.stream {
124        0 => id,
125        stream => format!("{id} :stream {stream}"),
126    };
127    match &response.payload {
128        ResponsePayload::Value(value) => format!("(:id {head} :value {})", format_value(value)),
129        ResponsePayload::Error {
130            code,
131            message,
132            detail,
133        } => {
134            let detail = detail
135                .as_ref()
136                .map(|detail| format!(" :detail {}", format_value(detail)))
137                .unwrap_or_default();
138            format!(
139                "(:id {head} :error (:code {} :message {}{detail}))",
140                code.as_symbol(),
141                format_value(&Value::String(message.clone()))
142            )
143        }
144    }
145}
146
147/// The response `frame` with `:notices` added when there are any.
148#[must_use]
149pub fn with_notices(frame: String, notices: &[String]) -> String {
150    match frame.strip_suffix(')') {
151        Some(head) if !notices.is_empty() => {
152            let items: Vec<String> = notices
153                .iter()
154                .map(|notice| format_value(&Value::String(notice.clone())))
155                .collect();
156            format!("{head} :notices ({}))", items.join(" "))
157        }
158        _ => frame,
159    }
160}
161
162fn format_id(id: &RequestId) -> String {
163    match id {
164        RequestId::Int(n) => n.to_string(),
165        RequestId::String(s) => format_value(&Value::String(s.clone())),
166    }
167}
168
169pub(crate) fn collect_plist(items: Vec<Expr>) -> Result<Vec<(String, Expr)>, EnvelopeError> {
170    if !items.len().is_multiple_of(2) {
171        return Err(EnvelopeError::NotPlist);
172    }
173    let mut pairs = Vec::with_capacity(items.len() / 2);
174    let mut iter = items.into_iter();
175    while let Some(key) = iter.next() {
176        let key_name = match key {
177            Expr::Keyword(name) => name,
178            _ => return Err(EnvelopeError::NotPlist),
179        };
180        let value = iter.next().ok_or(EnvelopeError::NotPlist)?;
181        pairs.push((key_name, value));
182    }
183    Ok(pairs)
184}
185
186pub(crate) fn expr_to_request_id(expr: &Expr) -> Result<RequestId, EnvelopeError> {
187    match expr {
188        Expr::Number(Number::Index(id)) => Ok(RequestId::Int(*id)),
189        Expr::Number(n @ Number::Scalar(_)) => Err(EnvelopeError::InvalidValue(
190            ":id",
191            format!("expected integer, got {n}"),
192        )),
193        Expr::String(s) => Ok(RequestId::String(s.clone())),
194        other => Err(EnvelopeError::InvalidValue(
195            ":id",
196            format!("expected integer or string, got {other:?}"),
197        )),
198    }
199}
200
201#[cfg(test)]
202mod tests;