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::{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            let deadline = Instant::now() + timeout;
87            loop {
88                check()?;
89                let remaining = deadline.saturating_duration_since(Instant::now());
90                if remaining.is_zero() {
91                    return Ok(None);
92                }
93                let notification = connection.poll(remaining.min(Duration::from_secs(1)))?;
94                // After waiting, this is an observed operation, not proof that
95                // a business request was never submitted. Preserve uncertainty.
96                check().map_err(|_| anyhow::anyhow!("Account notification session superseded"))?;
97                if notification.is_some() {
98                    return Ok(notification);
99                }
100            }
101        })
102    }
103}
104
105fn begin_push_request(client: &NativeClient, connected: u64) -> Result<(Exchange, AccountState)> {
106    let (exchange, state) = client
107        .owned_account()?
108        .begin()
109        .map_err(|error| error.context(NativeRequestNotSubmitted))?;
110    ensure!(
111        exchange.credential_generation == connected,
112        "Account notification credentials superseded"
113    );
114    Ok((exchange, state))
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120
121    #[test]
122    fn renewal_with_identical_keys_invalidates_an_existing_notification_transport() {
123        let client = super::super::tests::client();
124        let (first, _) = begin_push_request(&client, 0).unwrap();
125        drop(first);
126        let (renewal, same_credentials) = client.owned_account().unwrap().begin().unwrap();
127        renewal.accept_credentials(same_credentials).unwrap();
128        drop(renewal);
129        assert!(begin_push_request(&client, 0).is_err());
130        let (current, _) = begin_push_request(&client, 1).unwrap();
131        drop(current);
132        client.stop().unwrap();
133        let error = begin_push_request(&client, 1).err().unwrap();
134        assert!(error.is::<NativeRequestNotSubmitted>());
135        assert_eq!(client.account_status().unwrap().in_flight, 0);
136    }
137}