1use std::time::Instant;
5
6use serde::Serialize;
7use serde_json::{Map, Value, json};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
11#[serde(rename_all = "snake_case")]
12pub enum Outcome {
13 Done,
15 NotSent,
17 Unknown,
19}
20
21impl Outcome {
22 pub fn as_str(self) -> &'static str {
23 match self {
24 Outcome::Done => "done",
25 Outcome::NotSent => "not_sent",
26 Outcome::Unknown => "unknown",
27 }
28 }
29}
30
31#[derive(Debug, Clone)]
32pub struct Fail {
33 pub outcome: Outcome,
34 pub code: String,
35 pub message: String,
36 pub hint: Option<String>,
37 pub extra: Map<String, Value>,
39}
40
41pub type Fields = Map<String, Value>;
42pub type Res<T = Fields> = Result<T, Fail>;
43
44impl Fail {
45 pub fn new(outcome: Outcome, code: &str, message: impl Into<String>) -> Self {
46 Self {
47 outcome,
48 code: code.to_string(),
49 message: message.into(),
50 hint: None,
51 extra: Map::new(),
52 }
53 }
54
55 pub fn not_sent(code: &str, message: impl Into<String>) -> Self {
56 Self::new(Outcome::NotSent, code, message)
57 }
58
59 pub fn unknown(code: &str, message: impl Into<String>) -> Self {
60 Self::new(Outcome::Unknown, code, message)
61 }
62
63 pub fn invalid(message: impl Into<String>) -> Self {
64 Self::not_sent("invalid_argument", message)
65 }
66
67 pub fn hint(mut self, hint: impl Into<String>) -> Self {
68 self.hint = Some(hint.into());
69 self
70 }
71
72 pub fn with(mut self, key: &str, value: impl Into<Value>) -> Self {
73 self.extra.insert(key.to_string(), value.into());
74 self
75 }
76
77 pub fn error_json(&self) -> Value {
78 let mut e = json!({ "code": self.code, "message": self.message });
79 if let Some(h) = &self.hint {
80 e["hint"] = json!(h);
81 }
82 e
83 }
84}
85
86impl std::fmt::Display for Fail {
87 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88 write!(f, "{}: {}", self.code, self.message)
89 }
90}
91
92#[macro_export]
94macro_rules! fields {
95 ($($tt:tt)*) => {{
96 match ::serde_json::json!({ $($tt)* }) {
97 ::serde_json::Value::Object(m) => m,
98 _ => unreachable!(),
99 }
100 }};
101}
102
103pub fn envelope(result: Res, started: Instant) -> Value {
105 let elapsed = started.elapsed().as_millis() as u64;
106 let mut out = Map::new();
107 match result {
108 Ok(fields) => {
109 out.insert("ok".into(), json!(true));
110 out.insert("outcome".into(), json!(Outcome::Done.as_str()));
111 out.insert("elapsed_ms".into(), json!(elapsed));
112 for (k, v) in fields {
113 out.insert(k, v);
114 }
115 }
116 Err(fail) => {
117 out.insert("ok".into(), json!(false));
118 out.insert("outcome".into(), json!(fail.outcome.as_str()));
119 out.insert("error".into(), fail.error_json());
120 out.insert("elapsed_ms".into(), json!(elapsed));
121 for (k, v) in fail.extra {
122 out.insert(k, v);
123 }
124 }
125 }
126 Value::Object(out)
127}
128
129#[cfg(test)]
130mod tests {
131 use super::*;
132
133 #[test]
134 fn envelope_shapes() {
135 let ok = envelope(Ok(fields! {"sent": true}), Instant::now());
136 assert_eq!(ok["ok"], true);
137 assert_eq!(ok["outcome"], "done");
138 assert_eq!(ok["sent"], true);
139 assert!(ok.get("error").is_none());
140
141 let fail = envelope(
142 Err(Fail::not_sent("element_not_found", "no such element")
143 .hint("read the screen")
144 .with("candidates", "일반")),
145 Instant::now(),
146 );
147 assert_eq!(fail["ok"], false);
148 assert_eq!(fail["outcome"], "not_sent");
149 assert_eq!(fail["error"]["code"], "element_not_found");
150 assert_eq!(fail["error"]["hint"], "read the screen");
151 assert_eq!(fail["candidates"], "일반");
152 }
153}