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
pub mod abort;
pub mod authenticate;
pub mod call;
pub mod cancel;
pub mod challenge;
pub mod error;
pub mod event;
pub mod goodbye;
pub mod hello;
pub mod interrupt;
pub mod invocation;
pub mod publish;
pub mod published;
pub mod register;
pub mod registered;
pub mod result;
pub mod subscribe;
pub mod subscribed;
pub mod unregister;
pub mod unregistered;
pub mod unsubscribe;
pub mod unsubscribed;
pub mod welcome;
pub mod r#yield;

pub use abort::Abort;
pub use authenticate::Authenticate;
pub use call::Call;
pub use cancel::Cancel;
pub use challenge::Challenge;
pub use error::{WampError, WampErrorEvent};
pub use event::Event;
pub use goodbye::Goodbye;
pub use hello::Hello;
pub use interrupt::Interrupt;
pub use invocation::Invocation;
pub use publish::Publish;
pub use published::Published;
pub use r#yield::Yield;
pub use register::Register;
pub use registered::Registered;
pub use result::WampResult;
pub use subscribe::Subscribe;
pub use subscribed::Subscribed;
use tungstenite::Message;
pub use unregister::Unregister;
pub use unregistered::Unregistered;
pub use unsubscribe::Unsubscribe;
pub use unsubscribed::Unsubscribed;
pub use welcome::Welcome;

use serde::{de, Deserialize, Deserializer};
use serde_json::{from_str, from_value, json, Value};

use crate::roles::Roles;

/// # Message parsing helpers
///
/// These helpers are internal methods for parsing different aspects of each message.
/// This is very unorganized and could use some clarity.
///
/// The plan for current future releases is to make a macro that automatically
/// creates wamp message parsers, there are two main reasons for this.
///
/// > 1. Macros will allow for a "consistent" state of messages that does not change per instance.
/// >
/// > 2. Macros will allow for easy creation of WAMP "Extension" messages.
///
/// With that said, these helpers, while clear in definition, can be moved into the rest of the "macro"
/// code when the time comes, as that will be the primary implentation of the macro, is to create
/// the Serializer and Deserializer (as well as implement a couple other helper traits for the library)
///
/// There is a good change that at the point I am talking about, this will become its own proc macro crate.
pub(crate) mod helpers {

    use serde::{
        de::{self, SeqAccess},
        ser::Error,
        Deserialize, Serializer,
    };
    use serde_json::Value;
    use std::fmt::Display;

    use super::WampMessage;

    pub(crate) fn deser_seq_element<
        'de,
        T: PartialEq + Deserialize<'de>,
        E: Display,
        A: SeqAccess<'de>,
    >(
        seq: &mut A,
        error: E,
    ) -> Result<T, <A as SeqAccess<'de>>::Error> {
        let element: Option<T> = seq.next_element()?;
        if element != None {
            Ok(element.unwrap())
        } else {
            Err(serde::de::Error::custom(error))
        }
    }

    pub(crate) fn deser_args_kwargs_element<'de, E: Display, A: SeqAccess<'de>>(
        seq: &mut A,
        error: E,
    ) -> Result<Value, <A as SeqAccess<'de>>::Error> {
        let element: Option<Value> = seq.next_element()?;
        if let Some(element) = element {
            if element.is_object() || element.is_array() {
                Ok(element)
            } else {
                Err(serde::de::Error::custom(error))
            }
        } else {
            Ok(Value::Null)
        }
    }

    pub(crate) fn validate_id<'de, M: WampMessage, A: SeqAccess<'de>, E: Display>(
        id: &u64,
        name: E,
    ) -> Result<(), A::Error> {
        if &M::ID == id {
            Ok(())
        } else {
            Err(de::Error::custom(format!(
                "{name} has invalid ID {id}. The ID for {name} must be {}",
                M::ID
            )))
        }
    }

    pub(crate) fn deser_value_is_object<'de, A: SeqAccess<'de>, E: Display>(
        v: &Value,
        e: E,
    ) -> Result<(), A::Error> {
        if v.is_object() {
            Ok(())
        } else {
            Err(de::Error::custom(e))
        }
    }

    pub(crate) fn ser_value_is_object<S: Serializer, T: Display>(
        v: &Value,
        e: T,
    ) -> Result<&Value, S::Error> {
        if v.is_object() {
            Ok(v)
        } else {
            Err(S::Error::custom(e))
        }
    }

    pub(crate) fn ser_value_is_args<S: Serializer, T: Display>(
        v: &Value,
        e: T,
    ) -> Result<&Value, S::Error> {
        if v.is_array() || v.is_null() {
            Ok(v)
        } else {
            Err(S::Error::custom(e))
        }
    }

    pub(crate) fn ser_value_is_kwargs<S: Serializer, T: Display>(
        v: &Value,
        e: T,
    ) -> Result<&Value, S::Error> {
        if v.is_object() || v.is_null() {
            Ok(v)
        } else {
            Err(S::Error::custom(e))
        }
    }
}

#[derive(Debug, PartialEq, PartialOrd)]
/// # Message Direction
/// Indicates the Message Direction for a specified Role.
///
/// Receives means that the specified Role is allowed to receive the message.
/// Sends means that the specified Role allowed to send the message.
pub struct MessageDirection {
    pub receives: &'static bool,
    pub sends: &'static bool,
}

pub trait WampMessage {
    const ID: u64;

    /// # Direction method
    /// Indicates the Message Direction for a specified Role.
    ///
    /// Receives means that the specified Role is allowed to receive the message.
    /// Sends means that the specified Role allowed to send the message.
    fn direction(role: Roles) -> &'static MessageDirection;
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// # Messages Enum
/// This represents each of the messages described in the WAMP protocol.
///
/// This includes its own deserializer (you should serialize using the inner struct always).
///
/// It also implements `From<*n> for Messages` where n = each WAMP message.
/// # Examples
/// ```
/// use wamp_core::messages::{Call, Messages};
/// use wamp_core::call;
/// use serde_json::{Value, json, from_str};
///
/// let message = Messages::from(call!("topic"));
///
/// // Which is the same as this:
/// let mut message2 = Messages::Call(Call {
///     request_id: 1,
///     options: json!({}),
///     procedure: "topic".to_string(),
///     args: Value::Null,
///     kwargs: Value::Null
/// });
/// assert_eq!(message, message2);
///
/// // Lets make a raw string to pass to the deserializer (this is a Call message)
/// let data = r#"[48,1,{},"topic"]"#;
///
/// // Deserialize the raw string
/// let message3 = from_str::<Messages>(data).unwrap();
///
/// assert_eq!(message2, message3);
/// ```
pub enum Messages {
    Abort(Abort),
    Authenticate(Authenticate),
    Call(Call),
    Cancel(Cancel),
    Challenge(Challenge),
    Error(WampError),
    Event(Event),
    Goodbye(Goodbye),
    Hello(Hello),
    Interrupt(Interrupt),
    Invocation(Invocation),
    Publish(Publish),
    Published(Published),
    Register(Register),
    Registered(Registered),
    Result(WampResult),
    Subscribe(Subscribe),
    Subscribed(Subscribed),
    Unregister(Unregister),
    Unregistered(Unregistered),
    Unsubscribe(Unsubscribe),
    Unsubscribed(Unsubscribed),
    Welcome(Welcome),
    Yield(Yield),
    Extension(Vec<Value>),
}

impl Messages {
    /// # Get Message ID
    ///
    /// Get the message ID of a WAMP message. This uses the static u64 for any known WAMP messages.
    ///
    /// For Extension messages, it attempts to get the ID and returns None otherwise.
    ///
    /// ## Examples
    /// ```
    /// use wamp_core::call;
    /// use wamp_core::messages::Messages;
    ///
    /// let message = Messages::from(call!("topic"));
    ///
    /// let message_id = message.id();
    ///
    /// assert_eq!(message_id, Some(48));
    /// ```
    pub fn id(&self) -> Option<u64> {
        match self {
            Messages::Authenticate(_) => Some(Authenticate::ID),
            Messages::Abort(_) => Some(Abort::ID),
            Messages::Call(_) => Some(Call::ID),
            Messages::Cancel(_) => Some(Cancel::ID),
            Messages::Challenge(_) => Some(Authenticate::ID),
            Messages::Error(_) => Some(WampError::ID),
            Messages::Event(_) => Some(Event::ID),
            Messages::Goodbye(_) => Some(Goodbye::ID),
            Messages::Hello(_) => Some(Hello::ID),
            Messages::Interrupt(_) => Some(Interrupt::ID),
            Messages::Invocation(_) => Some(Invocation::ID),
            Messages::Publish(_) => Some(Publish::ID),
            Messages::Published(_) => Some(Published::ID),
            Messages::Register(_) => Some(Register::ID),
            Messages::Registered(_) => Some(Registered::ID),
            Messages::Result(_) => Some(WampResult::ID),
            Messages::Subscribe(_) => Some(Subscribe::ID),
            Messages::Subscribed(_) => Some(Subscribed::ID),
            Messages::Unregister(_) => Some(Unregister::ID),
            Messages::Unregistered(_) => Some(Unregistered::ID),
            Messages::Unsubscribe(_) => Some(Unsubscribe::ID),
            Messages::Unsubscribed(_) => Some(Unsubscribed::ID),
            Messages::Welcome(_) => Some(Welcome::ID),
            Messages::Yield(_) => Some(Yield::ID),
            Messages::Extension(values) => {
                if let Some(value) = values.first() {
                    value.as_u64()
                } else {
                    None
                }
            }
        }
    }
}

macro_rules! try_from_messages {
    ($i: ident) => {
        impl From<$i> for Messages {
            fn from(v: $i) -> Messages {
                Messages::$i(v)
            }
        }

        impl From<Messages> for $i {
            fn from(v: Messages) -> $i {
                v.into()
            }
        }
    };
}

try_from_messages!(Abort);
try_from_messages!(Authenticate);
try_from_messages!(Call);
try_from_messages!(Cancel);
try_from_messages!(Challenge);

// Created manually because the enum member name is not the same as struct name.
impl From<WampError> for Messages {
    fn from(v: WampError) -> Self {
        Messages::Error(v)
    }
}

impl TryFrom<Messages> for WampError {
    type Error = crate::error::Error;
    fn try_from(v: Messages) -> Result<WampError, Self::Error> {
        if let Messages::Error(v) = v {
            Ok(v)
        } else {
            Err(crate::error::Error::InvalidMessageEnumMember)
        }
    }
}

impl TryFrom<tungstenite::Message> for Messages {
    type Error = crate::error::Error;

    fn try_from(value: Message) -> Result<Self, crate::error::Error> {
        Ok(from_str(value.to_text()?)?)
    }
}

impl From<WampResult> for Messages {
    fn from(v: WampResult) -> Self {
        Messages::Result(v)
    }
}

impl TryFrom<Messages> for WampResult {
    type Error = crate::error::Error;
    fn try_from(v: Messages) -> Result<WampResult, Self::Error> {
        if let Messages::Result(v) = v {
            Ok(v)
        } else {
            Err(crate::error::Error::InvalidMessageEnumMember)
        }
    }
}

try_from_messages!(Event);
try_from_messages!(Goodbye);
try_from_messages!(Hello);
try_from_messages!(Interrupt);
try_from_messages!(Invocation);
try_from_messages!(Publish);
try_from_messages!(Published);
try_from_messages!(Register);
try_from_messages!(Registered);
try_from_messages!(Subscribe);
try_from_messages!(Subscribed);
try_from_messages!(Unregister);
try_from_messages!(Unregistered);
try_from_messages!(Unsubscribe);
try_from_messages!(Unsubscribed);
try_from_messages!(Welcome);
try_from_messages!(Yield);

impl<'de> Deserialize<'de> for Messages {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let wamp_components: Vec<Value> = Deserialize::deserialize(deserializer)?;
        let wamp_message_id = match wamp_components.first() {
            Some(v) => match v.as_u64() {
                Some(v) => Ok(v),
                None => Err(de::Error::custom("")),
            },
            None => Err(de::Error::custom("value")),
        }?;

        fn helper<'d, T, D>(wamp_components: Vec<Value>) -> Result<T, D::Error>
        where
            T: for<'de> Deserialize<'de>,
            D: Deserializer<'d>,
        {
            let value: T = from_value(json!(wamp_components)).map_err(de::Error::custom)?;
            Ok(value)
        }

        match wamp_message_id {
            Abort::ID => Ok(Self::Abort(helper::<Abort, D>(wamp_components)?)),
            Authenticate::ID => Ok(Self::Authenticate(helper::<Authenticate, D>(
                wamp_components,
            )?)),
            Call::ID => Ok(Self::Call(helper::<Call, D>(wamp_components)?)),
            Cancel::ID => Ok(Self::Cancel(helper::<Cancel, D>(wamp_components)?)),
            Challenge::ID => Ok(Self::Challenge(helper::<Challenge, D>(wamp_components)?)),
            WampError::ID => Ok(Self::Error(helper::<WampError, D>(wamp_components)?)),
            Event::ID => Ok(Self::Event(helper::<Event, D>(wamp_components)?)),
            Goodbye::ID => Ok(Self::Goodbye(helper::<Goodbye, D>(wamp_components)?)),
            Hello::ID => Ok(Self::Hello(helper::<Hello, D>(wamp_components)?)),
            Interrupt::ID => Ok(Self::Interrupt(helper::<Interrupt, D>(wamp_components)?)),
            Invocation::ID => Ok(Self::Invocation(helper::<Invocation, D>(wamp_components)?)),
            Publish::ID => Ok(Self::Publish(helper::<Publish, D>(wamp_components)?)),
            Published::ID => Ok(Self::Published(helper::<Published, D>(wamp_components)?)),
            Register::ID => Ok(Self::Register(helper::<Register, D>(wamp_components)?)),
            Registered::ID => Ok(Self::Registered(helper::<Registered, D>(wamp_components)?)),
            WampResult::ID => Ok(Self::Result(helper::<WampResult, D>(wamp_components)?)),
            Subscribe::ID => Ok(Self::Subscribe(helper::<Subscribe, D>(wamp_components)?)),
            Subscribed::ID => Ok(Self::Subscribed(helper::<Subscribed, D>(wamp_components)?)),
            Unregister::ID => Ok(Self::Unregister(helper::<Unregister, D>(wamp_components)?)),
            Unregistered::ID => Ok(Self::Unregistered(helper::<Unregistered, D>(
                wamp_components,
            )?)),
            Unsubscribe::ID => Ok(Self::Unsubscribe(helper::<Unsubscribe, D>(
                wamp_components,
            )?)),
            Unsubscribed::ID => Ok(Self::Unsubscribed(helper::<Unsubscribed, D>(
                wamp_components,
            )?)),
            Welcome::ID => Ok(Self::Welcome(helper::<Welcome, D>(wamp_components)?)),
            Yield::ID => Ok(Self::Yield(helper::<Yield, D>(wamp_components)?)),
            _ => Ok(Self::Extension(wamp_components)),
        }
    }
}