1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
|
use std::any::Any;
use std::collections::BTreeMap;
use std::error::Error;
use std::fmt::{Debug, Display};
use std::str::FromStr;
use crate::capabilities::{CapabilityRegistry, URN_JMAP_CORE};
use crate::types::*;
use serde::{Deserialize, Serialize};
// TODO: Move to an error module
pub type JMAPResult<T> = Result<T, JMAPError>;
#[derive(Debug)]
pub enum JMAPError {
ParseError(String),
DowncastError(String),
UnknownCapability(String),
UnknownMethod(String),
InvalidObject(String),
}
impl Display for JMAPError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self) //TODO: Make this less bad
}
}
impl Error for JMAPError {}
#[derive(Clone, PartialEq, PartialOrd, Ord, Eq, Debug)]
pub struct JMAPMethodName {
pub resource: String,
pub method: String,
}
impl JMAPMethodName {
pub fn new(resource: String, method: String) -> Self {
assert_ne!(resource.len(), 0);
assert_ne!(method.len(), 0);
Self { resource, method }
}
}
impl FromStr for JMAPMethodName {
type Err = JMAPError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut spl = s.split("/");
let resource = spl
.next()
.expect("Always at least one string expected from `split`")
.to_string();
let method = (match spl.next() {
Some(m) => {
if m.is_empty() {
Err(JMAPError::ParseError(
"Missing method name after '/'".to_string(),
))
} else {
Ok(m)
}
}
None => Err(JMAPError::ParseError("Missing '/' delimiter".to_string())),
})?
.to_string();
if let Some(t) = spl.next() {
Err(JMAPError::ParseError(format!(
"Additional '/' found => '/{}'",
t
)))
} else {
Ok(Self { resource, method })
}
}
}
impl Display for JMAPMethodName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}/{}", self.resource, self.method)
}
}
#[derive(Serialize, Deserialize, Clone)]
pub struct InvocationRaw(String, JObject, String);
pub trait JMAPInvocationArg: 'static + Sized {
const CAP_URN: &str;
const METHOD_HINT: &'static str;
fn from_obj(obj: &JObject) -> Self;
fn from_obj_dyn(obj: &JObject) -> Box<dyn JMAPInvocationArgDyn> {
Box::new(Self::from_obj(obj))
}
fn into_obj(self) -> JObject;
fn from_dyn(d: Box<dyn JMAPInvocationArgDyn>) -> JMAPResult<Box<Self>> {
let dyn_hint = d.get_method_hint();
if dyn_hint != Self::METHOD_HINT {
return Err(JMAPError::DowncastError(format!(
"Incompatible arguments: {} vs. {} ",
Self::METHOD_HINT,
dyn_hint
)));
}
let rf = Box::leak(d);
if let Some(anyref) = rf.as_any_mut().downcast_mut() {
// Safe because the reference is leaked from another box
unsafe { Ok(Box::from_raw(anyref)) }
} else {
// Safe because the reference is leaked from another box
unsafe {
// Free the memory
let b = Box::from_raw(rf);
drop(b)
}
Err(JMAPError::DowncastError(
"T is not the correct type despite having same method hint".to_string(),
))
}
}
}
pub trait JMAPInvocationArgDyn: 'static {
fn get_urn(&self) -> &'static str;
fn get_method_hint(&self) -> &'static str;
fn into_obj(self) -> JObject;
// Convert to any for downcasting, immutable
fn as_any(&self) -> &dyn Any;
/// Convert to any for downcasting, mutable
fn as_any_mut(&mut self) -> &mut dyn Any;
/// Convert to any for downcasting, consumes object
fn to_any(self) -> Box<dyn Any>;
}
impl<T: JMAPInvocationArg> JMAPInvocationArgDyn for T {
fn get_urn(&self) -> &'static str {
T::CAP_URN
}
fn get_method_hint(&self) -> &'static str {
T::METHOD_HINT
}
fn into_obj(self) -> JObject {
self.into_obj()
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn to_any(self) -> Box<dyn Any> {
Box::new(self)
}
}
pub struct Invocation<T: JMAPInvocationArg> {
pub method: JMAPMethodName,
pub arguments: T,
pub method_call_id: String,
}
impl<T: JMAPInvocationArg> Invocation<T> {
pub fn to_dyn(self) -> InvocationDyn {
InvocationDyn {
method: self.method,
arguments: Box::new(self.arguments),
method_call_id: self.method_call_id,
}
}
pub fn from_dyn(d: InvocationDyn) -> JMAPResult<Self> {
Ok(Self {
method: d.method,
arguments: *T::from_dyn(d.arguments)?,
method_call_id: d.method_call_id,
})
}
}
pub struct InvocationDyn {
method: JMAPMethodName,
arguments: Box<dyn JMAPInvocationArgDyn>,
method_call_id: String,
}
impl Debug for InvocationDyn {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"InvocationDyn({}, *, {})",
self.method, self.method_call_id
)
}
}
#[derive(Serialize, Deserialize, Clone)]
pub struct JMAPRequestRaw {
using: JArr<String>,
#[serde(rename = "methodCalls")]
method_calls: JArr<InvocationRaw>,
#[serde(rename = "createIds")]
create_ids: Option<JObj<JMAPId, JMAPId>>,
}
#[derive(Debug)]
pub struct JMAPRequest {
pub using: JArr<String>,
pub method_calls: JArr<JMAPResult<InvocationDyn>>,
pub create_ids: Option<JObj<JMAPId, JMAPId>>,
}
pub type MethodArgsParser = Box<fn(&JObject) -> Box<dyn JMAPInvocationArgDyn>>;
pub struct MethodRegistry(pub BTreeMap<JMAPMethodName, MethodArgsParser>);
impl Default for MethodRegistry {
fn default() -> Self {
Self::new()
}
}
impl MethodRegistry {
/// Create a collection of parsers
pub fn new() -> Self {
Self(BTreeMap::new())
}
/// Insert a parser
pub fn add_method<T: JMAPInvocationArg>(&mut self) {
self.0.insert(
T::METHOD_HINT
.parse()
.expect("METHOD_HINT needs to be a valid Method Name"),
Box::new(T::from_obj_dyn),
);
}
}
impl JMAPRequest {
pub fn from_raw(
raw: JMAPRequestRaw,
registry: &CapabilityRegistry,
fail_on_unknown_capability: bool,
) -> JMAPResult<Self> {
let using = raw.using;
let create_ids = raw.create_ids;
let mut method_registries = Vec::with_capacity(using.len());
let mut encountered_urns = Vec::with_capacity(using.len());
let mut has_core = false;
for cap_urn in using.iter() {
if cap_urn == URN_JMAP_CORE {
has_core = true;
}
if encountered_urns.contains(&cap_urn) {
return Err(JMAPError::InvalidObject(format!(
"Dupplicate capability {}",
cap_urn
)));
}
encountered_urns.push(cap_urn);
if let Some(method_reg) = registry.0.get(cap_urn) {
method_registries.push(&method_reg.methods);
} else if fail_on_unknown_capability {
return Err(JMAPError::UnknownCapability(cap_urn.clone()));
}
}
if !has_core {
return Err(JMAPError::InvalidObject(
"Missing core capability".to_string(),
));
}
let method_calls: Vec<JMAPResult<InvocationDyn>> = raw
.method_calls
.into_iter()
.map(|method_call| {
let mut method_parser_opt: Option<&MethodArgsParser> = None;
match method_call.0.parse() {
Ok(method_name) => {
for reg in method_registries.iter() {
if let Some(parser) = reg.0.get(&method_name) {
method_parser_opt = Some(parser);
break;
}
}
if let Some(method_parser) = method_parser_opt {
let method_args = method_parser(&method_call.1);
Ok(InvocationDyn {
method: method_name,
arguments: method_args,
method_call_id: method_call.2,
})
} else {
Err(JMAPError::UnknownMethod(method_name.to_string()))
}
}
Err(err) => Err(err),
}
})
.collect();
Ok(Self {
using,
method_calls,
create_ids,
})
}
}
#[cfg(test)]
mod test {
use jiff::fmt::rfc2822::parse;
use super::{JMAPRequest, JMAPRequestRaw};
use crate::capabilities::{CapabilityRegistry, CoreEchoArgs, URN_JMAP_CORE};
use crate::request::{Invocation, InvocationDyn, JMAPError};
use crate::{JMAPId, JUnknown};
use std::assert_matches;
use std::str::FromStr;
#[test]
fn test_jmap_request_parsing() {
let req = r#"{
"using": ["urn:ietf:params:jmap:core", "something_unknown"],
"methodCalls": [
[
"Core/Echo", {
"hello": "Hello world!"
},
"a"
],
[
"Unknown/Get", {
"something": "else"
},
"b"
]
],
"createIds": {
"i1": "id1"
}
}"#;
let reg = CapabilityRegistry::default();
let raw: JMAPRequestRaw = serde_json::from_str(req).unwrap();
let req_err = JMAPRequest::from_raw(raw.clone(), ®, true);
assert_matches!(req_err, Err(JMAPError::UnknownCapability(_)));
let req_ok = JMAPRequest::from_raw(raw, ®, false);
assert_matches!(
req_ok,
Ok(JMAPRequest {
using: _,
method_calls: _,
create_ids: _
})
);
let mut req_real = req_ok.expect("We tested this before");
assert_eq!(
req_real
.create_ids
.expect("We specified this in the test")
.get(&("i1".parse().unwrap()))
.expect("i1 Should be included")
.clone(),
JMAPId::from_str("id1").unwrap()
);
assert_eq!(req_real.using, vec![URN_JMAP_CORE, "something_unknown"]);
let unknown = req_real.method_calls.get(1).unwrap();
assert_matches!(unknown, Err(JMAPError::UnknownMethod(_)));
let echo = req_real.method_calls.remove(0).unwrap();
let invocation: Invocation<CoreEchoArgs> = Invocation::from_dyn(echo).unwrap();
assert_eq!(
invocation.arguments.obj.get("hello"),
Some(&JUnknown::String("Hello world!".to_string()))
);
}
}
|