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#[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 pub const BUSY: &str = "busy";
51 pub const TOO_MANY_STREAMS: &str = "too-many-streams";
53 pub const NO_CONVERSION: &str = "no-conversion";
65 pub const NOT_FOUND: &str = "not-found";
67 pub const UNAVAILABLE: &str = "unavailable";
70
71 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 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#[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;