1use super::*;
3use crate::{errors::AccountInterrupted, push, wire};
4use std::time::Instant;
5
6pub struct AccountPushConnection {
11 client: NativeClient,
12 connection: push::Connection,
13 credential_generation: u64,
14}
15
16impl NativeClient {
17 pub fn open_push_connection_blocking(&self) -> Result<AccountPushConnection> {
20 let owner = self.owned_account()?;
21 let (exchange, state) = owner
22 .begin()
23 .map_err(|error| error.context(NativeRequestNotSubmitted))?;
24 let credential_generation = exchange.credential_generation;
25 let options = self.options.clone();
26 let connection = Self::execute_account_request(
27 options.clone(),
28 exchange,
29 state,
30 owner.short_link.clone(),
31 Arc::new(AtomicBool::new(false)),
32 |_, state, check| {
33 check()?;
34 let connection =
35 push::Connection::open(state, options.timeout, options.receive_budget)?;
36 check()?;
38 Ok(connection)
39 },
40 )?;
41 Ok(AccountPushConnection {
42 client: self.clone(),
43 connection,
44 credential_generation,
45 })
46 }
47}
48
49impl AccountPushConnection {
50 fn request<T>(
51 &mut self,
52 operation: impl FnOnce(
53 &mut push::Connection,
54 &mut AccountState,
55 &dyn Fn() -> Result<()>,
56 ) -> Result<T>,
57 ) -> Result<T> {
58 let (exchange, state) = begin_push_request(&self.client, self.credential_generation)?;
59 NativeClient::execute_account_request(
60 self.client.options.clone(),
61 exchange,
62 state,
63 self.client.owned_account()?.short_link.clone(),
64 Arc::new(AtomicBool::new(false)),
65 |_, state, check| operation(&mut self.connection, state, check),
66 )
67 }
68
69 pub fn heartbeat(&mut self, cursor: &[u8]) -> Result<wire::Heartbeat> {
70 self.request(|connection, state, check| connection.heartbeat_guarded(state, cursor, check))
71 }
72
73 pub fn send_sticker_chunk_raw(
78 &mut self,
79 chunk: &crate::sticker_send::StickerSendChunk<'_>,
80 ) -> Result<Vec<u8>> {
81 self.request(|connection, state, check| {
82 connection.sticker_chunk_guarded(state, chunk, check)
83 })
84 }
85
86 pub fn sync(&mut self, cursor: &[u8], scene: u32) -> Result<wire::SyncBatch> {
87 self.request(|connection, state, check| {
88 connection.sync_guarded(state, cursor, scene, check)
89 })
90 }
91
92 pub fn poll(&mut self, timeout: Duration) -> Result<Option<push::Notification>> {
96 ensure!(
97 !timeout.is_zero() && timeout <= Duration::from_secs(300),
98 "Invalid account notification timeout"
99 );
100 self.request(|connection, _, check| {
101 wait_for_notification(timeout, check, |slice| connection.poll(slice))
102 })
103 }
104}
105
106fn wait_for_notification<T>(
109 timeout: Duration,
110 check: &dyn Fn() -> Result<()>,
111 mut wait: impl FnMut(Duration) -> Result<Option<T>>,
112) -> Result<Option<T>> {
113 let deadline = Instant::now() + timeout;
114 loop {
115 check()?;
116 let remaining = deadline.saturating_duration_since(Instant::now());
117 if remaining.is_zero() {
118 return Ok(None);
119 }
120 let notification = wait(remaining.min(Duration::from_secs(1)))?;
121 check().map_err(|error| {
124 let message = "Account notification session superseded";
125 match AccountInterrupted::find(&error) {
126 Some(reason) => reason.because(message),
127 None => anyhow::anyhow!(message),
128 }
129 })?;
130 if notification.is_some() {
131 return Ok(notification);
132 }
133 }
134}
135
136fn begin_push_request(client: &NativeClient, connected: u64) -> Result<(Exchange, AccountState)> {
137 let (exchange, state) = client
138 .owned_account()?
139 .begin()
140 .map_err(|error| error.context(NativeRequestNotSubmitted))?;
141 if exchange.credential_generation != connected {
142 return Err(AccountInterrupted::CredentialsSuperseded
143 .because("Account notification credentials superseded"));
144 }
145 Ok((exchange, state))
146}
147
148#[cfg(test)]
149mod tests {
150 use super::*;
151
152 #[test]
153 fn renewal_with_identical_keys_invalidates_an_existing_notification_transport() {
154 let client = super::super::tests::client();
155 let (first, _) = begin_push_request(&client, 0).unwrap();
156 drop(first);
157 let (renewal, same_credentials) = client.owned_account().unwrap().begin().unwrap();
158 renewal.accept_credentials(same_credentials).unwrap();
159 drop(renewal);
160 let error = begin_push_request(&client, 0).err().unwrap();
161 assert_eq!(
162 AccountInterrupted::find(&error),
163 Some(AccountInterrupted::CredentialsSuperseded)
164 );
165 assert_eq!(
166 error.to_string(),
167 "Account notification credentials superseded"
168 );
169 let (current, _) = begin_push_request(&client, 1).unwrap();
170 drop(current);
171 client.stop().unwrap();
172 let error = begin_push_request(&client, 1).err().unwrap();
173 assert!(error.is::<NativeRequestNotSubmitted>());
174 assert_eq!(
175 AccountInterrupted::find(&error),
176 Some(AccountInterrupted::Stopped)
177 );
178 assert_eq!(client.account_status().unwrap().in_flight, 0);
179 }
180
181 fn renew(client: &NativeClient) {
182 let (renewal, same_credentials) = client.owned_account().unwrap().begin().unwrap();
183 renewal.accept_credentials(same_credentials).unwrap();
184 }
185
186 fn interrupted_wait(
189 client: &NativeClient,
190 before_wait: impl FnOnce(),
191 during_wait: impl Fn(),
192 ) -> anyhow::Error {
193 before_wait();
194 client
195 .account_request_blocking(|_, _, check| {
196 wait_for_notification(Duration::from_secs(5), check, |_| {
197 during_wait();
198 Ok(Some(()))
199 })
200 })
201 .unwrap_err()
202 }
203
204 #[test]
205 fn stop_during_a_notification_wait_reports_stopped_without_claiming_unsent() {
206 let client = super::super::tests::client();
207 let error = interrupted_wait(&client, || (), || client.stop().unwrap());
208 assert_eq!(
209 AccountInterrupted::find(&error),
210 Some(AccountInterrupted::Stopped)
211 );
212 assert!(!error.is::<NativeRequestNotSubmitted>());
213 assert!(format!("{error:#}").contains("Account notification session superseded"));
214 assert_eq!(client.account_status().unwrap().in_flight, 0);
215 }
216
217 #[test]
218 fn renewal_during_a_notification_wait_reports_superseded_credentials() {
219 let client = super::super::tests::client();
220 let error = interrupted_wait(&client, || (), || renew(&client));
221 assert_eq!(
222 AccountInterrupted::find(&error),
223 Some(AccountInterrupted::CredentialsSuperseded)
224 );
225 assert!(!error.is::<NativeRequestNotSubmitted>());
226 assert!(format!("{error:#}").contains("Account notification session superseded"));
227 }
228
229 #[test]
230 fn transfer_before_a_request_reports_transferred() {
231 let client = super::super::tests::client();
232 client.shutdown_blocking().unwrap();
233 client.owned_account().unwrap().lock().unwrap().lifecycle = AccountLifecycle::Transferred;
234 let error = begin_push_request(&client, 0).err().unwrap();
235 assert_eq!(
236 AccountInterrupted::find(&error),
237 Some(AccountInterrupted::Transferred)
238 );
239 }
240
241 #[test]
242 fn a_wait_that_is_not_interrupted_returns_its_notification_or_times_out() {
243 let client = super::super::tests::client();
244 let received = client
245 .account_request_blocking(|_, _, check| {
246 wait_for_notification(Duration::from_secs(5), check, |_| Ok(Some(7)))
247 })
248 .unwrap();
249 assert_eq!(received, Some(7));
250 let quiet = client
251 .account_request_blocking(|_, _, check| {
252 wait_for_notification(Duration::from_millis(20), check, |slice| {
253 std::thread::sleep(slice);
254 Ok(None::<()>)
255 })
256 })
257 .unwrap();
258 assert_eq!(quiet, None);
259 }
260}