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