autopush_common/
notification.rs1use std::collections::HashMap;
3#[cfg(feature = "postgres")]
4use std::str::FromStr;
5
6use serde_derive::{Deserialize, Serialize};
7use uuid::Uuid;
8
9#[cfg(feature = "postgres")]
10use crate::db::error::DbError;
11use crate::util::ms_since_epoch;
12
13#[derive(Serialize, Default, Deserialize, Clone, Debug)]
14pub struct Notification {
18 #[serde(rename = "channelID")]
20 pub channel_id: Uuid,
21 pub version: String,
22 #[serde(skip_serializing)]
23 pub timestamp: u64,
24 #[serde(default = "default_ttl", skip_serializing)]
26 pub ttl: u64,
27 #[serde(skip_serializing)]
29 pub topic: Option<String>,
30 #[serde(skip_serializing_if = "Option::is_none")]
31 pub data: Option<String>,
32 #[serde(skip_serializing)]
33 pub sortkey_timestamp: Option<u64>,
34 #[serde(skip_serializing_if = "Option::is_none")]
35 pub headers: Option<HashMap<String, String>>,
36 #[serde(default, skip_serializing)]
39 pub received_ms: Option<u64>,
40 #[serde(skip_serializing_if = "Option::is_none")]
41 #[cfg(feature = "reliable_report")]
42 pub reliability_id: Option<String>,
43 #[cfg(feature = "reliable_report")]
44 #[serde(skip_serializing_if = "Option::is_none")]
45 pub reliable_state: Option<crate::reliability::ReliabilityState>,
46}
47
48pub const TOPIC_NOTIFICATION_PREFIX: &str = "01";
49pub const STANDARD_NOTIFICATION_PREFIX: &str = "02";
50
51impl Notification {
52 pub fn chidmessageid(&self) -> String {
63 let chid = self.channel_id.as_hyphenated();
64
65 if let Some(ref topic) = self.topic {
66 format!("{TOPIC_NOTIFICATION_PREFIX}:{chid}:{topic}")
67 } else if let Some(sortkey_timestamp) = self.sortkey_timestamp {
68 format!(
69 "{STANDARD_NOTIFICATION_PREFIX}:{}:{}",
70 if sortkey_timestamp == 0 {
71 ms_since_epoch()
72 } else {
73 sortkey_timestamp
74 },
75 chid
76 )
77 } else {
78 warn!("🚨 LEGACY MESSAGE!? {:?} ", self);
79 format!("{}:{}", chid, self.version)
81 }
82 }
83
84 pub fn expiry(&self) -> u64 {
85 self.timestamp + self.ttl
86 }
87
88 pub fn expired(&self, at_sec: u64) -> bool {
91 at_sec >= self.expiry()
92 }
93
94 #[cfg(feature = "reliable_report")]
95 pub async fn record_reliability(
96 &mut self,
97 reliability: &crate::reliability::PushReliability,
98 state: crate::reliability::ReliabilityState,
99 ) {
100 self.reliable_state = reliability
101 .record(
102 &self.reliability_id,
103 state,
104 &self.reliable_state,
105 Some(self.expiry()),
106 )
107 .await
108 .inspect_err(|e| {
109 warn!("🔍⚠️ Unable to record reliability state log: {:?}", e);
110 })
111 .unwrap_or(Some(state));
112 }
113
114 #[cfg(feature = "reliable_report")]
115 pub fn clone_without_reliability_state(&self) -> Self {
116 let mut cloned = self.clone();
117 cloned.reliable_state = None;
118 cloned
119 }
120}
121
122pub(crate) fn default_ttl() -> u64 {
123 0
124}
125
126#[cfg(feature = "postgres")]
127impl TryFrom<&sqlx::postgres::PgRow> for Notification {
129 type Error = DbError;
130
131 fn try_from(row: &sqlx::postgres::PgRow) -> Result<Self, Self::Error> {
132 #[cfg(feature = "reliable_report")]
133 use crate::reliability::ReliabilityState;
134 use sqlx::Row;
135 Ok(Self {
136 channel_id: row
137 .try_get::<&str, _>("channel_id")
138 .map(|v| Uuid::from_str(v).unwrap())
139 .unwrap(),
140 version: row.try_get::<String, _>("version").unwrap(),
141 ttl: row.try_get::<i64, _>("ttl").map(|v| v as u64).unwrap(),
142 topic: row
143 .try_get::<String, _>("topic")
144 .map(|v| if v.is_empty() { None } else { Some(v) })
145 .unwrap_or_default(),
146 timestamp: row
147 .try_get::<i64, _>("timestamp")
148 .map(|v| v as u64)
149 .unwrap(),
150 data: row.try_get::<String, _>("data").map(Some).unwrap(),
151 sortkey_timestamp: row
152 .try_get::<i64, _>("sortkey_timestamp")
153 .map(|v| Some(v as u64))
154 .unwrap_or_default(),
155 headers: row
156 .try_get::<&str, _>("headers")
157 .map(|v| {
158 if v.is_empty() || v == "null" || v == "{}" {
159 return None;
160 }
161 let hdrs: HashMap<String, String> = serde_json::from_str(v).unwrap();
162 Some(hdrs)
163 })
164 .unwrap_or_default(),
165 received_ms: None,
166 #[cfg(feature = "reliable_report")]
167 reliability_id: row.try_get::<String, _>("reliability_id").ok(),
168 #[cfg(feature = "reliable_report")]
169 reliable_state: row
170 .try_get::<&str, _>("reliable_state")
171 .map(|v| ReliabilityState::from_str(v).unwrap())
172 .ok(),
173 })
174 }
175}