Skip to main content

wechat_protocol/
account_push.rs

1//! Persistent notifications share the account owner, not a saved credential copy.
2use super::*;
3use crate::{errors::AccountInterrupted, push, wire};
4use std::time::Instant;
5
6/// Persistent account connection for callers that already own blocking workers.
7/// Requests and notification waits use the same account admission and handoff
8/// barriers as ordinary operations. Reconnect after a credential generation
9/// changes; an old authenticated socket cannot adopt newer credentials.
10pub struct AccountPushConnection {
11    client: NativeClient,
12    connection: push::Connection,
13    credential_generation: u64,
14}
15
16impl NativeClient {
17    /// Open an authenticated notification transport on the caller's blocking
18    /// worker. Creating the transport does not start a hidden executor or loop.
19    pub fn open_push_connection_blocking(&self) -> Result<AccountPushConnection> {
20        let (exchange, state) = self
21            .owned_account()?
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            Arc::new(AtomicBool::new(false)),
31            |_, state, check| {
32                check()?;
33                let connection =
34                    push::Connection::open(state, options.timeout, options.receive_budget)?;
35                // No business operation has been submitted by opening a socket.
36                check()?;
37                Ok(connection)
38            },
39        )?;
40        Ok(AccountPushConnection {
41            client: self.clone(),
42            connection,
43            credential_generation,
44        })
45    }
46}
47
48impl AccountPushConnection {
49    fn request<T>(
50        &mut self,
51        operation: impl FnOnce(
52            &mut push::Connection,
53            &mut AccountState,
54            &dyn Fn() -> Result<()>,
55        ) -> Result<T>,
56    ) -> Result<T> {
57        let (exchange, state) = begin_push_request(&self.client, self.credential_generation)?;
58        NativeClient::execute_account_request(
59            self.client.options.clone(),
60            exchange,
61            state,
62            Arc::new(AtomicBool::new(false)),
63            |_, state, check| operation(&mut self.connection, state, check),
64        )
65    }
66
67    pub fn heartbeat(&mut self, cursor: &[u8]) -> Result<wire::Heartbeat> {
68        self.request(|connection, state, check| connection.heartbeat_guarded(state, cursor, check))
69    }
70
71    pub fn sync(&mut self, cursor: &[u8], scene: u32) -> Result<wire::SyncBatch> {
72        self.request(|connection, state, check| {
73            connection.sync_guarded(state, cursor, scene, check)
74        })
75    }
76
77    /// Poll without an account lock. One-second slices observe account shutdown
78    /// during long waits. A notification is returned only while its socket's
79    /// credential generation remains current.
80    pub fn poll(&mut self, timeout: Duration) -> Result<Option<push::Notification>> {
81        ensure!(
82            !timeout.is_zero() && timeout <= Duration::from_secs(300),
83            "Invalid account notification timeout"
84        );
85        self.request(|connection, _, check| {
86            wait_for_notification(timeout, check, |slice| connection.poll(slice))
87        })
88    }
89}
90
91/// Wait in one-second slices so a stop or renewal ends the wait promptly. The
92/// reason for an interruption stays attached as [`AccountInterrupted`].
93fn wait_for_notification<T>(
94    timeout: Duration,
95    check: &dyn Fn() -> Result<()>,
96    mut wait: impl FnMut(Duration) -> Result<Option<T>>,
97) -> Result<Option<T>> {
98    let deadline = Instant::now() + timeout;
99    loop {
100        check()?;
101        let remaining = deadline.saturating_duration_since(Instant::now());
102        if remaining.is_zero() {
103            return Ok(None);
104        }
105        let notification = wait(remaining.min(Duration::from_secs(1)))?;
106        // After waiting, this is an observed operation, not proof that
107        // a business request was never submitted. Preserve uncertainty.
108        check().map_err(|error| {
109            let message = "Account notification session superseded";
110            match AccountInterrupted::find(&error) {
111                Some(reason) => reason.because(message),
112                None => anyhow::anyhow!(message),
113            }
114        })?;
115        if notification.is_some() {
116            return Ok(notification);
117        }
118    }
119}
120
121fn begin_push_request(client: &NativeClient, connected: u64) -> Result<(Exchange, AccountState)> {
122    let (exchange, state) = client
123        .owned_account()?
124        .begin()
125        .map_err(|error| error.context(NativeRequestNotSubmitted))?;
126    if exchange.credential_generation != connected {
127        return Err(AccountInterrupted::CredentialsSuperseded
128            .because("Account notification credentials superseded"));
129    }
130    Ok((exchange, state))
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    #[test]
138    fn renewal_with_identical_keys_invalidates_an_existing_notification_transport() {
139        let client = super::super::tests::client();
140        let (first, _) = begin_push_request(&client, 0).unwrap();
141        drop(first);
142        let (renewal, same_credentials) = client.owned_account().unwrap().begin().unwrap();
143        renewal.accept_credentials(same_credentials).unwrap();
144        drop(renewal);
145        let error = begin_push_request(&client, 0).err().unwrap();
146        assert_eq!(
147            AccountInterrupted::find(&error),
148            Some(AccountInterrupted::CredentialsSuperseded)
149        );
150        assert_eq!(
151            error.to_string(),
152            "Account notification credentials superseded"
153        );
154        let (current, _) = begin_push_request(&client, 1).unwrap();
155        drop(current);
156        client.stop().unwrap();
157        let error = begin_push_request(&client, 1).err().unwrap();
158        assert!(error.is::<NativeRequestNotSubmitted>());
159        assert_eq!(
160            AccountInterrupted::find(&error),
161            Some(AccountInterrupted::Stopped)
162        );
163        assert_eq!(client.account_status().unwrap().in_flight, 0);
164    }
165
166    fn renew(client: &NativeClient) {
167        let (renewal, same_credentials) = client.owned_account().unwrap().begin().unwrap();
168        renewal.accept_credentials(same_credentials).unwrap();
169    }
170
171    /// Run the notification wait inside an account request, with `during_wait`
172    /// standing in for the time spent blocked on the socket.
173    fn interrupted_wait(
174        client: &NativeClient,
175        before_wait: impl FnOnce(),
176        during_wait: impl Fn(),
177    ) -> anyhow::Error {
178        before_wait();
179        client
180            .account_request_blocking(|_, _, check| {
181                wait_for_notification(Duration::from_secs(5), check, |_| {
182                    during_wait();
183                    Ok(Some(()))
184                })
185            })
186            .unwrap_err()
187    }
188
189    #[test]
190    fn stop_during_a_notification_wait_reports_stopped_without_claiming_unsent() {
191        let client = super::super::tests::client();
192        let error = interrupted_wait(&client, || (), || client.stop().unwrap());
193        assert_eq!(
194            AccountInterrupted::find(&error),
195            Some(AccountInterrupted::Stopped)
196        );
197        assert!(!error.is::<NativeRequestNotSubmitted>());
198        assert!(format!("{error:#}").contains("Account notification session superseded"));
199        assert_eq!(client.account_status().unwrap().in_flight, 0);
200    }
201
202    #[test]
203    fn renewal_during_a_notification_wait_reports_superseded_credentials() {
204        let client = super::super::tests::client();
205        let error = interrupted_wait(&client, || (), || renew(&client));
206        assert_eq!(
207            AccountInterrupted::find(&error),
208            Some(AccountInterrupted::CredentialsSuperseded)
209        );
210        assert!(!error.is::<NativeRequestNotSubmitted>());
211        assert!(format!("{error:#}").contains("Account notification session superseded"));
212    }
213
214    #[test]
215    fn transfer_before_a_request_reports_transferred() {
216        let client = super::super::tests::client();
217        client.shutdown_blocking().unwrap();
218        client.owned_account().unwrap().lock().unwrap().lifecycle = AccountLifecycle::Transferred;
219        let error = begin_push_request(&client, 0).err().unwrap();
220        assert_eq!(
221            AccountInterrupted::find(&error),
222            Some(AccountInterrupted::Transferred)
223        );
224    }
225
226    #[test]
227    fn a_wait_that_is_not_interrupted_returns_its_notification_or_times_out() {
228        let client = super::super::tests::client();
229        let received = client
230            .account_request_blocking(|_, _, check| {
231                wait_for_notification(Duration::from_secs(5), check, |_| Ok(Some(7)))
232            })
233            .unwrap();
234        assert_eq!(received, Some(7));
235        let quiet = client
236            .account_request_blocking(|_, _, check| {
237                wait_for_notification(Duration::from_millis(20), check, |slice| {
238                    std::thread::sleep(slice);
239                    Ok(None::<()>)
240                })
241            })
242            .unwrap();
243        assert_eq!(quiet, None);
244    }
245}