1
use nomiscript::{Expr, Number, Value, format_value};
2
use thiserror::Error;
3

            
4
#[derive(Debug, Clone, PartialEq, Eq)]
5
pub enum RequestId {
6
    Int(i64),
7
    String(String),
8
}
9

            
10
#[derive(Debug, Clone, PartialEq)]
11
pub 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)]
24
pub struct ErrorCode(String);
25

            
26
impl ErrorCode {
27
3282216
    pub fn new(symbol: impl Into<String>) -> Self {
28
3282216
        Self(symbol.into())
29
3282216
    }
30

            
31
    #[must_use]
32
3279045
    pub fn as_symbol(&self) -> &str {
33
3279045
        &self.0
34
3279045
    }
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)]
83
pub 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)]
93
pub 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)]
101
pub 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

            
118
mod frame;
119
pub use frame::{Frame, read_frame};
120

            
121
3446928
pub fn format_response(response: &Response) -> String {
122
3446928
    let id = format_id(&response.id);
123
3446928
    let head = match response.stream {
124
3441567
        0 => id,
125
5361
        stream => format!("{id} :stream {stream}"),
126
    };
127
3446928
    match &response.payload {
128
215829
        ResponsePayload::Value(value) => format!("(:id {head} :value {})", format_value(value)),
129
        ResponsePayload::Error {
130
            code,
131
            message,
132
            detail,
133
        } => {
134
3231099
            let detail = detail
135
3231099
                .as_ref()
136
31161
                .map(|detail| format!(" :detail {}", format_value(detail)))
137
                .unwrap_or_default();
138
3231099
            format!(
139
3231099
                "(:id {head} :error (:code {} :message {}{detail}))",
140
3231099
                code.as_symbol(),
141
3231099
                format_value(&Value::String(message.clone()))
142
            )
143
        }
144
    }
145
3446928
}
146

            
147
/// The response `frame` with `:notices` added when there are any.
148
#[must_use]
149
230987
pub fn with_notices(frame: String, notices: &[String]) -> String {
150
230987
    match frame.strip_suffix(')') {
151
230987
        Some(head) if !notices.is_empty() => {
152
1605
            let items: Vec<String> = notices
153
1605
                .iter()
154
1606
                .map(|notice| format_value(&Value::String(notice.clone())))
155
                .collect();
156
1605
            format!("{head} :notices ({}))", items.join(" "))
157
        }
158
229382
        _ => frame,
159
    }
160
230987
}
161

            
162
3446928
fn format_id(id: &RequestId) -> String {
163
3446928
    match id {
164
3446924
        RequestId::Int(n) => n.to_string(),
165
4
        RequestId::String(s) => format_value(&Value::String(s.clone())),
166
    }
167
3446928
}
168

            
169
527850
pub(crate) fn collect_plist(items: Vec<Expr>) -> Result<Vec<(String, Expr)>, EnvelopeError> {
170
527850
    if !items.len().is_multiple_of(2) {
171
        return Err(EnvelopeError::NotPlist);
172
527850
    }
173
527850
    let mut pairs = Vec::with_capacity(items.len() / 2);
174
527850
    let mut iter = items.into_iter();
175
1620067
    while let Some(key) = iter.next() {
176
1092217
        let key_name = match key {
177
1092217
            Expr::Keyword(name) => name,
178
            _ => return Err(EnvelopeError::NotPlist),
179
        };
180
1092217
        let value = iter.next().ok_or(EnvelopeError::NotPlist)?;
181
1092217
        pairs.push((key_name, value));
182
    }
183
527850
    Ok(pairs)
184
527850
}
185

            
186
10445803
pub(crate) fn expr_to_request_id(expr: &Expr) -> Result<RequestId, EnvelopeError> {
187
10445803
    match expr {
188
10445636
        Expr::Number(Number::Index(id)) => Ok(RequestId::Int(*id)),
189
2
        Expr::Number(n @ Number::Scalar(_)) => Err(EnvelopeError::InvalidValue(
190
2
            ":id",
191
2
            format!("expected integer, got {n}"),
192
2
        )),
193
164
        Expr::String(s) => Ok(RequestId::String(s.clone())),
194
1
        other => Err(EnvelopeError::InvalidValue(
195
1
            ":id",
196
1
            format!("expected integer or string, got {other:?}"),
197
1
        )),
198
    }
199
10445803
}
200

            
201
#[cfg(test)]
202
mod tests;