Skip to main content

waft_embedder/
service_extensions.rs

1//! What a service extension call carries between a host and the framework: its parameters, and
2//! its answer or the reason it has none.
3//!
4//! Flutter's service extensions are `dart:developer`'s: a method name beginning `ext.`, string
5//! parameters, and a JSON answer, which the Dart VM service carries to a client. Here the
6//! framework keeps the extensions (`waft_foundation::ServiceExtensions`) and a host carries the
7//! calls ([`EmbedderClient::service_extension_call`](crate::EmbedderClient::service_extension_call)),
8//! so these are the types both sides read.
9
10use std::collections::BTreeMap;
11use std::fmt;
12
13/// One call's parameters: Dart's `Map<String, String>`, as a client sends them.
14#[derive(Clone, Debug, Default, PartialEq, Eq)]
15pub struct ServiceExtensionParams(BTreeMap<String, String>);
16
17impl ServiceExtensionParams {
18    /// The parameters `pairs` names.
19    pub fn new(pairs: impl IntoIterator<Item = (String, String)>) -> ServiceExtensionParams {
20        ServiceExtensionParams(pairs.into_iter().collect())
21    }
22
23    /// The value of `name`, when the client sent it.
24    pub fn get(&self, name: &str) -> Option<&str> {
25        self.0.get(name).map(String::as_str)
26    }
27
28    /// The value of `name`, or the error a client is answered when a required one is missing.
29    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    /// Every parameter, by name.
35    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
42/// What a service extension answers: Dart's `ServiceExtensionResponse.result`, the JSON a
43/// callback's map encodes to, or the reason there is none.
44pub type ServiceExtensionResult = Result<serde_json::Value, ServiceExtensionError>;
45
46/// Why a call has no answer: the errors Dart's `ServiceExtensionResponse.error` reports.
47#[derive(Clone, Debug, PartialEq, Eq)]
48pub enum ServiceExtensionError {
49    /// No extension of that name is registered; `registered` names those that are, so a client
50    /// can tell what this app serves.
51    Unknown {
52        name: String,
53        registered: Vec<String>,
54    },
55    /// The parameters do not fit the extension: Dart's `invalidParams`.
56    InvalidParams(String),
57    /// The extension failed while answering: Dart's `extensionError`.
58    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
79/// One call from a client, which a host hands the framework through
80/// [`EmbedderClient::service_extension_call`](crate::EmbedderClient::service_extension_call).
81pub struct ServiceExtensionCall {
82    /// The extension's whole name, as `ext.waft.debugDumpApp`.
83    pub name: String,
84    pub params: ServiceExtensionParams,
85    /// Where the answer goes.
86    pub reply: ServiceExtensionReply,
87}
88
89/// The answer to one call, given once, as [`AppExitReply`](crate::AppExitReply) is. Dropped
90/// unanswered, it answers [`ServiceExtensionError::Failed`], so a client is never left waiting.
91pub struct ServiceExtensionReply(Option<Box<dyn FnOnce(ServiceExtensionResult)>>);
92
93impl ServiceExtensionReply {
94    /// A reply that hands its answer to `send`. The answer is given inside a call into the
95    /// client, so `send` may only post it to the host's own loop or thread, never call the
96    /// client.
97    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}