Skip to main content

autoconnect_common/
protocol.rs

1//! Definition of Internal Router and Websocket protocol messages
2//!
3//! This module is a structured definition of several protocol. Both
4//! messages received from the client and messages sent from the server are
5//! defined here. The `derive(Deserialize)` and `derive(Serialize)` annotations
6//! are used to generate the ability to serialize these structures to JSON,
7//! using the `serde` crate. More docs for serde can be found at
8//! <https://serde.rs>
9use std::collections::HashMap;
10use std::str::FromStr;
11
12use serde_derive::{Deserialize, Serialize};
13use strum_macros::{AsRefStr, Display, EnumString};
14use uuid::Uuid;
15
16use autopush_common::notification::Notification;
17
18/// Message types for WebPush protocol messages.
19///
20/// This enum should be used instead of string literals when referring to message types.
21/// String serialization is handled automatically via the strum traits.
22///
23/// Example:
24/// ```
25///  use autoconnect_common::protocol::MessageType;
26///
27/// let message_type = MessageType::Hello;
28/// let message_str = message_type.as_ref();  // Returns "hello"
29/// ```
30#[derive(Debug, Clone, Copy, PartialEq, Eq, AsRefStr, Display, EnumString)]
31#[strum(serialize_all = "snake_case")]
32pub enum MessageType {
33    Hello,
34    Register,
35    Unregister,
36    BroadcastSubscribe,
37    Ack,
38    Nack,
39    Ping,
40    Notification,
41    Broadcast,
42}
43
44impl MessageType {
45    /// Returns the expected message type string for error messages
46    pub fn expected_msg(&self) -> String {
47        format!(r#"Expected messageType="{}""#, self.as_ref())
48    }
49}
50
51#[derive(Debug, Eq, PartialEq, Serialize)]
52#[serde(untagged)]
53pub enum BroadcastValue {
54    Value(String),
55    Nested(HashMap<String, BroadcastValue>),
56}
57
58#[derive(Debug, Default)]
59// Used for the server to flag a webpush client to deliver a Notification or Check storage
60// Nearly every value sent is a Notification, so boxing it wouldn't save memory.
61#[allow(clippy::large_enum_variant)]
62pub enum ServerNotification {
63    CheckStorage,
64    Notification(Notification),
65    #[default]
66    Disconnect,
67}
68
69#[derive(Debug, Deserialize)]
70#[serde(tag = "messageType", rename_all = "snake_case")]
71pub enum ClientMessage {
72    Hello {
73        uaid: Option<String>,
74        #[serde(rename = "channelIDs", skip_serializing_if = "Option::is_none")]
75        _channel_ids: Option<Vec<Uuid>>,
76        #[serde(skip_serializing_if = "Option::is_none")]
77        broadcasts: Option<HashMap<String, String>>,
78    },
79
80    Register {
81        #[serde(rename = "channelID")]
82        channel_id: String,
83        key: Option<String>,
84    },
85
86    Unregister {
87        #[serde(rename = "channelID")]
88        channel_id: Uuid,
89        code: Option<u32>,
90    },
91
92    BroadcastSubscribe {
93        broadcasts: HashMap<String, String>,
94    },
95
96    Ack {
97        updates: Vec<ClientAck>,
98    },
99
100    Nack {
101        code: Option<i32>,
102        version: String,
103    },
104
105    Ping,
106}
107
108impl ClientMessage {
109    /// Get the message type of this message
110    pub fn message_type(&self) -> MessageType {
111        match self {
112            ClientMessage::Hello { .. } => MessageType::Hello,
113            ClientMessage::Register { .. } => MessageType::Register,
114            ClientMessage::Unregister { .. } => MessageType::Unregister,
115            ClientMessage::BroadcastSubscribe { .. } => MessageType::BroadcastSubscribe,
116            ClientMessage::Ack { .. } => MessageType::Ack,
117            ClientMessage::Nack { .. } => MessageType::Nack,
118            ClientMessage::Ping => MessageType::Ping,
119        }
120    }
121}
122
123impl FromStr for ClientMessage {
124    type Err = serde_json::error::Error;
125
126    fn from_str(s: &str) -> Result<Self, Self::Err> {
127        // parse empty object "{}" as a Ping
128        serde_json::from_str::<HashMap<(), ()>>(s)
129            .map(|_| ClientMessage::Ping)
130            .or_else(|_| serde_json::from_str(s))
131    }
132}
133
134/// Returned ACKnowledgement of the received message by the User Agent.
135/// This is the payload for the `messageType:ack` packet.
136///
137#[derive(Debug, Deserialize)]
138pub struct ClientAck {
139    /// The channel_id which received messages
140    #[serde(rename = "channelID")]
141    pub channel_id: Uuid,
142    /// The corresponding version number for the message.
143    pub version: String,
144    /// An optional code categorizing the status of the ACK
145    pub code: Option<u16>,
146}
147
148impl ClientAck {
149    #[cfg(feature = "reliable_report")]
150    pub fn reliability_state(&self) -> autopush_common::reliability::ReliabilityState {
151        match self.code.unwrap_or(100) {
152            101 => autopush_common::reliability::ReliabilityState::DecryptionError,
153            102 => autopush_common::reliability::ReliabilityState::NotDelivered,
154            // 100 (ignore/treat anything else as 100)
155            _ => autopush_common::reliability::ReliabilityState::Delivered,
156        }
157    }
158}
159
160#[derive(Debug, Serialize)]
161#[serde(tag = "messageType", rename_all = "snake_case")]
162pub enum ServerMessage {
163    Hello {
164        uaid: String,
165        status: u32,
166        // This is required for output, but will always be "true"
167        use_webpush: bool,
168        broadcasts: HashMap<String, BroadcastValue>,
169    },
170
171    Register {
172        #[serde(rename = "channelID")]
173        channel_id: Uuid,
174        status: u32,
175        #[serde(rename = "pushEndpoint")]
176        push_endpoint: String,
177    },
178
179    Unregister {
180        #[serde(rename = "channelID")]
181        channel_id: Uuid,
182        status: u32,
183    },
184
185    Broadcast {
186        broadcasts: HashMap<String, BroadcastValue>,
187    },
188
189    Notification(Notification),
190
191    Ping,
192}
193
194impl ServerMessage {
195    /// Get the message type of this message
196    pub fn message_type(&self) -> MessageType {
197        match self {
198            ServerMessage::Hello { .. } => MessageType::Hello,
199            ServerMessage::Register { .. } => MessageType::Register,
200            ServerMessage::Unregister { .. } => MessageType::Unregister,
201            ServerMessage::Broadcast { .. } => MessageType::Broadcast,
202            ServerMessage::Notification(..) => MessageType::Notification,
203            ServerMessage::Ping => MessageType::Ping,
204        }
205    }
206
207    pub fn to_json(&self) -> Result<String, serde_json::error::Error> {
208        match self {
209            // Both client and server understand the verbose `{"messageType": "ping"}` and the abbreviated `{}`
210            // as valid ping messages. The server defaults to the shorter `{}` form.
211            ServerMessage::Ping => Ok("{}".to_string()),
212            _ => serde_json::to_string(self),
213        }
214    }
215}