Skip to main content

wechat_protocol/
account_request.rs

1//! Scoped operations for embedders that already execute on blocking workers.
2use super::*;
3
4/// A single logical operation borrowing this client's temporary request state.
5/// It is not an account owner and cannot outlive request_blocking. No operation
6/// accepts an independently mutable AccountState. Use ordinary async client
7/// methods unless the embedding application already owns a blocking worker.
8pub struct AccountRequest<'a> {
9    transport: &'a NativeClient,
10    state: &'a mut AccountState,
11    spent: bool,
12}
13
14macro_rules! operation {
15    ($name:ident($($arg:ident: $ty:ty),*) -> $result:ty => $raw:ident) => {
16        pub fn $name(&mut self, $($arg: $ty),*) -> Result<$result> {
17            self.admit()?;
18            self.transport.$raw(self.state, $($arg),*)
19        }
20    };
21}
22
23impl AccountRequest<'_> {
24    fn admit(&mut self) -> Result<()> {
25        // A second operation must not label the first possibly accepted one
26        // "not submitted". Each logical request has its own outcome/journal.
27        ensure!(!self.spent, "Account request context already consumed");
28        self.spent = true;
29        Ok(())
30    }
31
32    /// Read-only request context for protocol preparation and journal binding.
33    /// These secret bytes are not an independent account owner or a handoff.
34    pub fn account(&self) -> &AccountState {
35        self.state
36    }
37
38    operation!(sync(cursor: &[u8]) -> crate::SyncBatch => sync_snapshot);
39    operation!(sync_scene(cursor: &[u8], scene: u32) -> crate::SyncBatch => sync_scene_snapshot);
40    operation!(heartbeat(cursor: &[u8]) -> crate::Heartbeat => heartbeat_snapshot);
41    operation!(lookup_contacts(ids: &[String]) -> crate::ContactLookup => lookup_contacts_snapshot);
42    operation!(lookup_room(room: &str, version: u32) -> crate::RoomRoster => lookup_room_snapshot);
43    operation!(init_contacts(contact_sequence: u32, room_sequence: u32) -> crate::InitContactPage => init_contacts_snapshot);
44    operation!(download_avatars(ids: &[String]) -> Vec<crate::AvatarBytes> => download_avatars_snapshot);
45    operation!(download_voice_chunk(server_id: u64, length: u32, offset: u32) -> crate::VoiceChunk => download_voice_chunk_snapshot);
46    operation!(cdn_config() -> crate::media::CdnConfig => cdn_config_snapshot);
47    operation!(large_cdn_config(route: crate::media::LargeCdnRoute) -> crate::media::CdnConfig => large_cdn_config_snapshot);
48    operation!(group_inventory(cursor: &[u8]) -> crate::GroupMetadataPage => group_inventory_snapshot);
49    operation!(lookup_contacts_raw(ids: &[String]) -> Vec<u8> => lookup_contacts_raw_snapshot);
50    operation!(lookup_contacts_receipt(ids: &[String]) -> crate::MetadataReply<crate::ContactLookup> => lookup_contacts_receipt_snapshot);
51    operation!(lookup_room_raw(room: &str, version: u32) -> Vec<u8> => lookup_room_raw_snapshot);
52    operation!(lookup_room_receipt(room: &str, version: u32) -> crate::MetadataReply<crate::RoomRoster> => lookup_room_receipt_snapshot);
53    operation!(init_contacts_receipt(contacts: u32, rooms: u32) -> crate::MetadataReply<crate::InitContactPage> => init_contacts_receipt_snapshot);
54    operation!(group_detail_raw(group: &str) -> Vec<u8> => group_detail_raw_snapshot);
55    operation!(group_mutation_raw(request: &crate::GroupRpc) -> Vec<u8> => group_mutation_raw_snapshot);
56    operation!(recall_message(request: &crate::MessageRecall) -> crate::MessageRecallReply => recall_message_snapshot);
57    operation!(notify_read_session(request: &crate::SessionReadNotification) -> crate::SessionReadReply => notify_read_session_snapshot);
58    operation!(contact_sync(cursor: &[u8], message_cursor: &[u8], continuation: bool) -> crate::contact_sync::ContactSyncBatch => contact_sync_snapshot);
59    operation!(send_share(destination: &str, client_id: &str, created_at: u32, content: &str) -> crate::media_send::MediaSendResult => send_share_snapshot);
60    operation!(send_quote(destination: &str, client_id: &str, created_at: u32, content: &str, source: Option<&str>) -> crate::media_send::MediaSendResult => send_quote_with_source_snapshot);
61    operation!(reserve_file_upload(destination: &str, client_id: &str, name: &str, length: usize, md5: &str) -> crate::file_upload::FileUploadReservation => reserve_file_upload_snapshot);
62    operation!(send_file(destination: &str, client_id: &str, created_at: u32, upload: &crate::media::UploadedMedia, reservation: Option<&crate::file_upload::FileUploadReservation>) -> crate::media_send::MediaSendResult => send_file_with_reservation_snapshot);
63    operation!(send_image(destination: &str, client_id: &str, upload: &crate::media::UploadedImage) -> crate::media_send::MediaSendResult => send_image_snapshot);
64    operation!(send_video(destination: &str, client_id: &str, upload: &crate::media::UploadedVideo, seconds: u32) -> crate::media_send::MediaSendResult => send_video_snapshot);
65    operation!(send_voice(destination: &str, client_id: &str, created_at: u32, duration_ms: u32, encoded: &[u8]) -> crate::media_send::MediaSendResult => send_voice_snapshot);
66
67    pub fn send_text(
68        &mut self,
69        destination: &str,
70        content: &str,
71        options: &TextSendOptions,
72    ) -> Result<crate::TextSendResult> {
73        self.send_text_guarded(destination, content, options, || Ok(()))
74    }
75
76    pub fn send_text_guarded(
77        &mut self,
78        destination: &str,
79        content: &str,
80        options: &TextSendOptions,
81        before_submit: impl FnOnce() -> Result<()>,
82    ) -> Result<crate::TextSendResult> {
83        self.admit()?;
84        let request = crate::wire::text_send_request_with_source(
85            destination,
86            content,
87            options.created_at,
88            options.client_message_id,
89            options.source.as_deref(),
90        )?;
91        let reply = self.transport.authenticated_rpc_guarded(
92            self.state,
93            522,
94            "/cgi-bin/micromsg-bin/newsendmsg",
95            &request,
96            before_submit,
97        )?;
98        crate::wire::decode_text_send(&reply, destination, options.client_message_id)
99    }
100
101    pub fn call_rpc(
102        &mut self,
103        route: crate::calls::host_policy::CallHostRoute,
104        request: &[u8],
105        before_submit: impl FnOnce() -> Result<()>,
106        retain_reply: impl FnOnce(&[u8]) -> Result<()>,
107    ) -> Result<Vec<u8>> {
108        self.admit()?;
109        let cookie = Zeroizing::new(self.state.cookie.clone());
110        let reply =
111            self.transport
112                .call_rpc_snapshot_guarded(self.state, route, request, before_submit)?;
113        if let Err(error) = retain_reply(&reply) {
114            // Retention failure cannot publish this request's new cookie. A
115            // concurrent accepted account update is still protected by revision.
116            zeroize::Zeroize::zeroize(&mut self.state.cookie);
117            self.state.cookie = cookie.to_vec();
118            return Err(error);
119        }
120        Ok(reply)
121    }
122
123    /// Read-only call polling on an existing blocking worker. The caller owns
124    /// the async wait/cancellation mechanism; this context retains the account
125    /// lease until that transport future is dropped or completes.
126    pub fn call_live_sync(
127        &mut self,
128        request: &[u8],
129        wait_timeout: Duration,
130        before_submit: impl FnOnce() -> Result<()>,
131        wait: impl for<'a> FnOnce(
132            std::pin::Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send + 'a>>,
133        ) -> Result<Vec<u8>>,
134        retain_reply: impl FnOnce(&[u8]) -> Result<()>,
135    ) -> Result<Vec<u8>> {
136        self.admit()?;
137        let cookie = Zeroizing::new(self.state.cookie.clone());
138        let reply = self.transport.call_live_sync_snapshot_with_wait_timeout(
139            self.state,
140            request,
141            wait_timeout,
142            before_submit,
143            wait,
144        )?;
145        if let Err(error) = retain_reply(&reply) {
146            zeroize::Zeroize::zeroize(&mut self.state.cookie);
147            self.state.cookie = cookie.to_vec();
148            return Err(error);
149        }
150        Ok(reply)
151    }
152}
153
154impl NativeClient {
155    /// Change transport deadlines/budgets for a handle while retaining the same
156    /// account owner and admission rules. This never imports credential state.
157    pub fn with_request_options(&self, options: NativeOptions) -> Result<Self> {
158        // Reuse constructor validation without replacing the account owner.
159        let mut handle = Self::new(options)?;
160        handle.account = Some(self.owned_account()?.clone());
161        Ok(handle)
162    }
163
164    /// Execute one scoped account operation on the caller's blocking worker.
165    /// Uses the same admission, generation, storage and handoff barriers as async
166    /// operations. No executor or independent credential owner is constructed.
167    pub fn request_blocking<T>(
168        &self,
169        operation: impl FnOnce(&mut AccountRequest<'_>) -> Result<T>,
170    ) -> Result<T> {
171        self.account_request_blocking(|transport, state, _| {
172            operation(&mut AccountRequest {
173                transport,
174                state,
175                spent: false,
176            })
177        })
178    }
179
180    /// Explicit authentication renewal on an existing blocking worker. This
181    /// never retries the operation whose rejection prompted the caller to renew.
182    pub fn renew_session_blocking(&self, computer_name: &str) -> Result<()> {
183        let (exchange, state) = self
184            .owned_account()?
185            .begin()
186            .map_err(|error| error.context(NativeRequestNotSubmitted))?;
187        let exchange = Arc::new(exchange);
188        let mut transport = Self::new(self.options.clone())?;
189        let submission = exchange.clone();
190        transport.submission_guard = Some(Arc::new(move || {
191            submission
192                .check()
193                .map_err(|error| error.context(NativeRequestNotSubmitted))
194        }));
195        let accepted = transport.renew_session_snapshot(&state, computer_name)?;
196        exchange.accept_credentials(accepted)
197    }
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203
204    #[test]
205    fn scoped_requests_share_owner_and_cannot_submit_after_stop() {
206        let client = super::super::tests::client();
207        let other = client
208            .with_request_options(NativeOptions::default())
209            .unwrap();
210        other
211            .request_blocking(|request| {
212                assert_eq!(request.account().uin, 1);
213                request.admit()?;
214                request.state.cookie = vec![4];
215                Ok(())
216            })
217            .unwrap();
218        assert_eq!(client.export_account_state().unwrap().cookie, vec![4]);
219        client.stop().unwrap();
220        let entered = AtomicBool::new(false);
221        let error = other
222            .request_blocking(|_| {
223                entered.store(true, Ordering::Release);
224                Ok(())
225            })
226            .unwrap_err();
227        assert!(error.is::<NativeRequestNotSubmitted>());
228        assert!(!entered.load(Ordering::Acquire));
229    }
230
231    #[test]
232    fn scoped_context_cannot_turn_a_second_operation_into_an_unsent_retry() {
233        let client = super::super::tests::client();
234        let error = client
235            .request_blocking(|request| {
236                request.admit()?;
237                request.state.cookie = vec![7];
238                request.admit()
239            })
240            .unwrap_err();
241        assert!(!error.is::<NativeRequestNotSubmitted>());
242        assert_eq!(client.export_account_state().unwrap().cookie, vec![7]);
243        assert_eq!(client.account_status().unwrap().in_flight, 0);
244    }
245
246    #[tokio::test]
247    async fn blocking_workers_and_async_requests_share_one_response_order() {
248        let client = super::super::tests::client();
249        let old = client.clone();
250        let (ready, ready_rx) = tokio::sync::oneshot::channel();
251        let (finish, finish_rx) = std::sync::mpsc::channel();
252        let worker = tokio::task::spawn_blocking(move || {
253            old.request_blocking(|request| {
254                request.admit()?;
255                ready.send(()).unwrap();
256                finish_rx.recv()?;
257                request.state.cookie = vec![1];
258                Ok(())
259            })
260        });
261        ready_rx.await.unwrap();
262        client
263            .account_request(|_, state, _| {
264                state.cookie = vec![2];
265                Ok(())
266            })
267            .await
268            .unwrap();
269        finish.send(()).unwrap();
270        worker.await.unwrap().unwrap();
271        assert_eq!(client.export_account_state().unwrap().cookie, vec![2]);
272    }
273}