waft_embedder/
service_extensions.rs1use std::collections::BTreeMap;
11use std::fmt;
12
13#[derive(Clone, Debug, Default, PartialEq, Eq)]
15pub struct ServiceExtensionParams(BTreeMap<String, String>);
16
17impl ServiceExtensionParams {
18 pub fn new(pairs: impl IntoIterator<Item = (String, String)>) -> ServiceExtensionParams {
20 ServiceExtensionParams(pairs.into_iter().collect())
21 }
22
23 pub fn get(&self, name: &str) -> Option<&str> {
25 self.0.get(name).map(String::as_str)
26 }
27
28 pub fn require(&self, name: &str) -> Result<&str, ServiceExtensionError> {
30 self.get(name)
31 .ok_or_else(|| ServiceExtensionError::InvalidParams(format!("`{name}` is required")))
32 }
33
34 pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
36 self.0
37 .iter()
38 .map(|(name, value)| (name.as_str(), value.as_str()))
39 }
40}
41
42pub type ServiceExtensionResult = Result<serde_json::Value, ServiceExtensionError>;
45
46#[derive(Clone, Debug, PartialEq, Eq)]
48pub enum ServiceExtensionError {
49 Unknown {
52 name: String,
53 registered: Vec<String>,
54 },
55 InvalidParams(String),
57 Failed(String),
59}
60
61impl fmt::Display for ServiceExtensionError {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 match self {
64 ServiceExtensionError::Unknown { name, registered } => write!(
65 f,
66 "no service extension `{name}` is registered; this app serves {}",
67 registered.join(", ")
68 ),
69 ServiceExtensionError::InvalidParams(reason) => {
70 write!(f, "invalid parameters: {reason}")
71 }
72 ServiceExtensionError::Failed(reason) => f.write_str(reason),
73 }
74 }
75}
76
77impl std::error::Error for ServiceExtensionError {}
78
79pub struct ServiceExtensionCall {
82 pub name: String,
84 pub params: ServiceExtensionParams,
85 pub reply: ServiceExtensionReply,
87}
88
89pub struct ServiceExtensionReply(Option<Box<dyn FnOnce(ServiceExtensionResult)>>);
92
93impl ServiceExtensionReply {
94 pub fn new(send: impl FnOnce(ServiceExtensionResult) + 'static) -> ServiceExtensionReply {
98 ServiceExtensionReply(Some(Box::new(send)))
99 }
100
101 pub fn answer(mut self, result: ServiceExtensionResult) {
102 self.send(result);
103 }
104
105 fn send(&mut self, result: ServiceExtensionResult) {
106 if let Some(send) = self.0.take() {
107 send(result);
108 }
109 }
110}
111
112impl Drop for ServiceExtensionReply {
113 fn drop(&mut self) {
114 self.send(Err(ServiceExtensionError::Failed(
115 "the app let go of the call without answering it".to_owned(),
116 )));
117 }
118}
119
120impl fmt::Debug for ServiceExtensionReply {
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 f.debug_struct("ServiceExtensionReply")
123 .field("answered", &self.0.is_none())
124 .finish()
125 }
126}
127
128#[cfg(test)]
129mod tests {
130 use std::cell::RefCell;
131 use std::rc::Rc;
132
133 use super::*;
134
135 #[test]
136 fn a_reply_dropped_unanswered_answers_that_it_failed() {
137 let answered = Rc::new(RefCell::new(None));
138 let to = Rc::clone(&answered);
139 drop(ServiceExtensionReply::new(move |result| {
140 *to.borrow_mut() = Some(result)
141 }));
142 assert!(matches!(
143 answered.borrow().as_ref(),
144 Some(Err(ServiceExtensionError::Failed(_)))
145 ));
146 }
147
148 #[test]
149 fn a_reply_answers_once() {
150 let answers = Rc::new(RefCell::new(Vec::new()));
151 let to = Rc::clone(&answers);
152 ServiceExtensionReply::new(move |result| to.borrow_mut().push(result))
153 .answer(Ok(serde_json::json!({ "data": "tree" })));
154 assert_eq!(
155 *answers.borrow(),
156 [Ok(serde_json::json!({ "data": "tree" }))]
157 );
158 }
159}