summaryrefslogtreecommitdiff
path: root/src/request.rs
blob: 301cd2e167f3ce3d830f4726f6d984115af1439b (plain)
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
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) -> JMAPResult<Self>;
    fn from_obj_dyn(obj: &JObject) -> JMAPResult<Box<dyn JMAPInvocationArgDyn>> {
        let arg = Self::from_obj(obj)?;
        Ok(Box::new(arg))
    }
    fn into_obj(self) -> JMAPResult<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: Box<Self>) -> JMAPResult<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: Box<Self>) -> JMAPResult<JObject> {
        T::into_obj(*self)
    }

    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 fn to_raw(self) -> JMAPResult<InvocationRaw> {
        let args = self.arguments.into_obj()?; 
        Ok(InvocationRaw (
           self.method.to_string(), 
           args, 
           self.method_call_id
        ))
    }

    pub fn new(arguments: T, method_call_id: String) -> Self {
        Self {
            method: T::METHOD_HINT.parse().expect("METHOD_HINT MUST Contain a valid method name"),
            arguments, 
            method_call_id,
        }
    }
}

pub struct InvocationDyn {
    method: JMAPMethodName,
    arguments: Box<dyn JMAPInvocationArgDyn>,
    method_call_id: String,
}

impl InvocationDyn {
    pub fn to_raw(self) -> JMAPResult<InvocationRaw>{
        let args = self.arguments; 
        let args_obj = args.into_obj()?;
        Ok(InvocationRaw (
           self.method.to_string(), 
           args_obj, 
           self.method_call_id
        ))

    }
}

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")]
    #[serde(skip_serializing_if = "Option::is_none")]
    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) -> JMAPResult<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 Default for JMAPRequest {
    fn default() -> Self {
        Self {
            using: vec![URN_JMAP_CORE.to_string()],
            method_calls: vec![],
            create_ids: None,
        }
    }
} 


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,
        })
    }

    pub fn to_raw(self) -> JMAPResult<JMAPRequestRaw> {
        let mut method_calls = Vec::with_capacity(self.method_calls.len());
        for mcr in self.method_calls {
            let mc = mcr?;
            method_calls.push(mc.to_raw()?) 
        }
         
        Ok(JMAPRequestRaw { 
            using: self.using, 
            method_calls,
            create_ids: self.create_ids 
        })
    }  

    pub fn add_invocation<T: JMAPInvocationArg>(&mut self, invocation: Invocation<T>) -> JMAPResult<()>{
        match self.using.iter().find(|x| x.as_str() == T::CAP_URN) {
            Some(_) => {},
            None => { self.using.push(T::CAP_URN.to_string()); } // TODO: Turn into set
        }
        self.method_calls.push(Ok(invocation.to_dyn()));    
        Ok(())
    }
}

#[cfg(test)]
mod test {
    use jiff::fmt::rfc2822::parse;
use serde_json::json;

    use super::{JMAPRequest, JMAPRequestRaw};
    use crate::capabilities::{CapabilityRegistry, CoreEchoArgs, URN_JMAP_CORE};
    use crate::request::{Invocation, InvocationDyn, JMAPError, JMAPResult};
    use crate::{JMAPId, JObject, 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_ok = JMAPRequest::from_raw(raw, &reg, 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()))
        );
    }
    #[test] 
    fn unknown_capability() {
        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(), &reg, true);
        assert_matches!(req_err, JMAPResult::Err(JMAPError::UnknownCapability(_)))
    }

    #[test] 
    fn dupplicate_capability() {        
         let req = r#"{
            "using": ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:core"], 
            "methodCalls": [
                [
                  "Core/Echo", {
                    "hello": "Hello world!" 
                  }, 
                  "a"
                ] 
            ],
            "createIds": {
                "i1": "id1"
            } 
        }"#;
        let reg = CapabilityRegistry::default();
        let raw: JMAPRequestRaw = serde_json::from_str(req).unwrap();
        let req_err = JMAPRequest::from_raw(raw.clone(), &reg, true);
        assert_matches!(req_err, JMAPResult::Err(JMAPError::InvalidObject(_)))
    }

    #[test]
    fn builder() {
        let mut req = JMAPRequest::default(); 
        let content: JObject = serde_json::from_value(json!(
            {
                "hello": "Hello world!"
            }
        )).unwrap();
        let echo = CoreEchoArgs {obj: content} ; 
        let inv = Invocation::new(echo, "a".to_string()); 
        req.add_invocation(inv).unwrap();   

        let rraw = req.to_raw().unwrap(); 
        let exp = json!({
            "using": ["urn:ietf:params:jmap:core"], 
            "methodCalls": [
                [
                    "Core/Echo", 
                    {
                        "hello": "Hello world!"
                    }, 
                    "a"
                ]
            ]
        });
        assert_eq!(serde_json::to_value(&rraw).unwrap(), exp);
    }
}