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    /// Submit one direct sticker upload chunk. Journal the attempt before calling;
25    /// an error after submission has an uncertain outcome and is not a retry grant.
26    pub fn upload_sticker_chunk(
27        &mut self,
28        source: &[u8],
29        offset: u32,
30    ) -> Result<crate::sticker_upload::StickerUploadAcknowledgement> {
31        self.admit()?;
32        self.transport
33            .upload_sticker_chunk_snapshot(self.state, source, offset)
34    }
35
36    /// Return one custom-list or metadata reply for caller-owned receipt retention.
37    /// The request must come from the bounded custom-sticker builders.
38    pub fn custom_stickers_raw(&mut self, request: &[u8]) -> Result<Vec<u8>> {
39        self.admit()?;
40        ensure!(request.len() <= 65536, "sticker_request_limit");
41        self.transport.authenticated_rpc(
42            self.state,
43            697,
44            "/cgi-bin/micromsg-bin/mmbatchemojidownload",
45            request,
46        )
47    }
48    /// Submit one journaled Saved membership/placement intent, returning even a
49    /// rejected service reply before decoding. A transport error is uncertain.
50    pub fn mutate_custom_sticker(
51        &mut self,
52        id: &str,
53        action: &crate::custom_stickers::CustomStickerMutation,
54    ) -> Result<Vec<u8>> {
55        let request = crate::custom_stickers::custom_sticker_mutation_request(id, action)?;
56        self.admit()?;
57        self.transport.authenticated_rpc(
58            self.state,
59            698,
60            "/cgi-bin/micromsg-bin/mmbackupemojioperate",
61            &request,
62        )
63    }
64    /// Submit one direct upload chunk and return its raw acknowledgement for
65    /// retention before validation. Callers must journal each attempted offset.
66    pub fn upload_sticker_chunk_raw(&mut self, source: &[u8], offset: u32) -> Result<Vec<u8>> {
67        let request = crate::sticker_upload::sticker_upload_request(source, offset)?;
68        self.admit()?;
69        self.transport.authenticated_rpc(
70            self.state,
71            703,
72            "/cgi-bin/micromsg-bin/mmemojiupload",
73            &request,
74        )
75    }
76
77    /// Read a native pack-list page for durable caller-owned receipt storage.
78    pub fn sticker_pack_page_raw(
79        &mut self,
80        feed: crate::sticker_packs::StickerPackFeed,
81        cursor: &[u8],
82    ) -> Result<Vec<u8>> {
83        let request = crate::sticker_packs::sticker_pack_list_request(self.state, feed, cursor)?;
84        self.admit()?;
85        self.transport
86            .sticker_pack_rpc_snapshot(self.state, 411, &request)
87    }
88    /// Read full metadata/content references for one product without acquiring media.
89    pub fn sticker_pack_detail_raw(&mut self, id: &str) -> Result<Vec<u8>> {
90        let request = crate::sticker_packs::sticker_pack_detail_request(self.state, id)?;
91        self.admit()?;
92        self.transport
93            .sticker_pack_rpc_snapshot(self.state, 412, &request)
94    }
95    /// Read localized caption rows for one product, retaining the complete reply.
96    pub fn sticker_pack_captions_raw(&mut self, id: &str) -> Result<Vec<u8>> {
97        let request = crate::sticker_packs::sticker_pack_captions_request(self.state, id)?;
98        self.admit()?;
99        self.transport
100            .sticker_pack_rpc_snapshot(self.state, 521, &request)
101    }
102    /// Submit one journaled eligible-free membership change. The caller checks
103    /// eligibility before adding, retains this reply and reconciles membership.
104    /// A transport error is uncertain and never an automatic retry grant.
105    pub fn sticker_pack_membership_raw(&mut self, id: &str, added: bool) -> Result<Vec<u8>> {
106        let request = crate::sticker_packs::sticker_pack_membership_request(self.state, id, added)?;
107        self.admit()?;
108        self.transport
109            .sticker_pack_rpc_snapshot(self.state, 413, &request)
110    }
111
112    /// Acquire one archive locator without changing pack membership. Journal the
113    /// attempt before calling and retain the raw reply before decoding it.
114    pub fn sticker_pack_acquisition_raw(&mut self, id: &str) -> Result<Vec<u8>> {
115        let request = crate::sticker_packs::sticker_pack_acquisition_request(self.state, id)?;
116        self.admit()?;
117        self.transport
118            .sticker_pack_rpc_snapshot(self.state, 423, &request)
119    }
120
121    /// Submit one journaled probe or byte continuation for a single sticker send.
122    /// Return raw bytes for durable retention before validating acknowledgement.
123    pub fn send_sticker_chunk_raw(
124        &mut self,
125        chunk: &crate::sticker_send::StickerSendChunk<'_>,
126    ) -> Result<Vec<u8>> {
127        let request = crate::sticker_send::sticker_send_request(self.state, chunk)?;
128        self.admit()?;
129        self.transport.authenticated_rpc(
130            self.state,
131            175,
132            "/cgi-bin/micromsg-bin/sendemoji",
133            &request,
134        )
135    }
136
137    fn admit(&mut self) -> Result<()> {
138        // A second operation must not label the first possibly accepted one
139        // "not submitted". Each logical request has its own outcome/journal.
140        ensure!(!self.spent, "Account request context already consumed");
141        self.spent = true;
142        Ok(())
143    }
144
145    /// Read-only request context for protocol preparation and journal binding.
146    /// These secret bytes are not an independent account owner or a handoff.
147    pub fn account(&self) -> &AccountState {
148        self.state
149    }
150
151    /// Read one exact OpenIM contact using optional group context and a supplied ticket.
152    pub fn lookup_openim_contact(
153        &mut self,
154        username: &str,
155        room: Option<&str>,
156        ticket: Option<&str>,
157    ) -> Result<crate::OpenImContact> {
158        self.admit()?;
159        self.transport
160            .openim_contact_snapshot(self.state, username, room, ticket)
161    }
162
163    /// Return the authenticated OpenIM reply bytes for caller-owned receipt storage and decoding.
164    pub fn lookup_openim_contact_raw(
165        &mut self,
166        username: &str,
167        room: Option<&str>,
168        ticket: Option<&str>,
169    ) -> Result<Vec<u8>> {
170        self.admit()?;
171        self.transport
172            .openim_contact_raw_snapshot(self.state, username, room, ticket)
173    }
174
175    operation!(sync(cursor: &[u8]) -> crate::SyncBatch => sync_snapshot);
176    operation!(sync_scene(cursor: &[u8], scene: u32) -> crate::SyncBatch => sync_scene_snapshot);
177    operation!(heartbeat(cursor: &[u8]) -> crate::Heartbeat => heartbeat_snapshot);
178    operation!(lookup_contacts(ids: &[String]) -> crate::ContactLookup => lookup_contacts_snapshot);
179    operation!(lookup_room(room: &str, version: u32) -> crate::RoomRoster => lookup_room_snapshot);
180    operation!(init_contacts(contact_sequence: u32, room_sequence: u32) -> crate::InitContactPage => init_contacts_snapshot);
181    operation!(download_avatars(ids: &[String]) -> Vec<crate::AvatarBytes> => download_avatars_snapshot);
182    operation!(download_voice_chunk(server_id: u64, length: u32, offset: u32) -> crate::VoiceChunk => download_voice_chunk_snapshot);
183    operation!(cdn_config() -> crate::media::CdnConfig => cdn_config_snapshot);
184    operation!(large_cdn_config(route: crate::media::LargeCdnRoute) -> crate::media::CdnConfig => large_cdn_config_snapshot);
185    operation!(group_inventory(cursor: &[u8]) -> crate::GroupMetadataPage => group_inventory_snapshot);
186    operation!(lookup_contacts_raw(ids: &[String]) -> Vec<u8> => lookup_contacts_raw_snapshot);
187    operation!(lookup_contacts_receipt(ids: &[String]) -> crate::MetadataReply<crate::ContactLookup> => lookup_contacts_receipt_snapshot);
188    operation!(lookup_room_raw(room: &str, version: u32) -> Vec<u8> => lookup_room_raw_snapshot);
189    operation!(lookup_room_receipt(room: &str, version: u32) -> crate::MetadataReply<crate::RoomRoster> => lookup_room_receipt_snapshot);
190    operation!(init_contacts_receipt(contacts: u32, rooms: u32) -> crate::MetadataReply<crate::InitContactPage> => init_contacts_receipt_snapshot);
191    operation!(group_detail_raw(group: &str) -> Vec<u8> => group_detail_raw_snapshot);
192    operation!(group_mutation_raw(request: &crate::GroupRpc) -> Vec<u8> => group_mutation_raw_snapshot);
193    operation!(recall_message(request: &crate::MessageRecall) -> crate::MessageRecallReply => recall_message_snapshot);
194    operation!(notify_read_session(request: &crate::SessionReadNotification) -> crate::SessionReadReply => notify_read_session_snapshot);
195    operation!(contact_sync(cursor: &[u8], message_cursor: &[u8], continuation: bool) -> crate::contact_sync::ContactSyncBatch => contact_sync_snapshot);
196    operation!(send_share(destination: &str, client_id: &str, created_at: u32, content: &str) -> crate::media_send::MediaSendResult => send_share_snapshot);
197    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);
198    operation!(reserve_file_upload(destination: &str, client_id: &str, name: &str, length: usize, md5: &str) -> crate::file_upload::FileUploadReservation => reserve_file_upload_snapshot);
199    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);
200    /// Submit the uploaded standard and thumbnail copies, including an original when present.
201    pub fn send_image(
202        &mut self,
203        destination: &str,
204        client_id: &str,
205        upload: &crate::media::UploadedImage,
206    ) -> Result<crate::media_send::MediaSendResult> {
207        self.admit()?;
208        self.transport
209            .send_image_snapshot(self.state, destination, client_id, upload)
210    }
211
212    operation!(send_video(destination: &str, client_id: &str, upload: &crate::media::UploadedVideo, seconds: u32) -> crate::media_send::MediaSendResult => send_video_snapshot);
213    operation!(send_voice(destination: &str, client_id: &str, created_at: u32, duration_ms: u32, encoded: &[u8]) -> crate::media_send::MediaSendResult => send_voice_snapshot);
214
215    pub fn send_text(
216        &mut self,
217        destination: &str,
218        content: &str,
219        options: &TextSendOptions,
220    ) -> Result<crate::TextSendResult> {
221        self.send_text_guarded(destination, content, options, || Ok(()))
222    }
223
224    pub fn send_text_guarded(
225        &mut self,
226        destination: &str,
227        content: &str,
228        options: &TextSendOptions,
229        before_submit: impl FnOnce() -> Result<()>,
230    ) -> Result<crate::TextSendResult> {
231        self.admit()?;
232        let request = crate::wire::text_send_request_with_source(
233            destination,
234            content,
235            options.created_at,
236            options.client_message_id,
237            options.source.as_deref(),
238        )?;
239        let reply = self.transport.authenticated_rpc_guarded(
240            self.state,
241            522,
242            "/cgi-bin/micromsg-bin/newsendmsg",
243            &request,
244            before_submit,
245        )?;
246        crate::wire::decode_text_send(&reply, destination, options.client_message_id)
247    }
248
249    pub fn call_rpc(
250        &mut self,
251        route: crate::calls::host_policy::CallHostRoute,
252        request: &[u8],
253        before_submit: impl FnOnce() -> Result<()>,
254        retain_reply: impl FnOnce(&[u8]) -> Result<()>,
255    ) -> Result<Vec<u8>> {
256        self.admit()?;
257        let cookie = Zeroizing::new(self.state.cookie.clone());
258        let reply =
259            self.transport
260                .call_rpc_snapshot_guarded(self.state, route, request, before_submit)?;
261        if let Err(error) = retain_reply(&reply) {
262            // Retention failure cannot publish this request's new cookie. A
263            // concurrent accepted account update is still protected by revision.
264            zeroize::Zeroize::zeroize(&mut self.state.cookie);
265            self.state.cookie = cookie.to_vec();
266            return Err(error);
267        }
268        Ok(reply)
269    }
270
271    /// Read-only call polling on an existing blocking worker. The caller owns
272    /// the async wait/cancellation mechanism; this context retains the account
273    /// lease until that transport future is dropped or completes.
274    pub fn call_live_sync(
275        &mut self,
276        request: &[u8],
277        wait_timeout: Duration,
278        before_submit: impl FnOnce() -> Result<()>,
279        wait: impl for<'a> FnOnce(
280            std::pin::Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send + 'a>>,
281        ) -> Result<Vec<u8>>,
282        retain_reply: impl FnOnce(&[u8]) -> Result<()>,
283    ) -> Result<Vec<u8>> {
284        self.admit()?;
285        let cookie = Zeroizing::new(self.state.cookie.clone());
286        let reply = self.transport.call_live_sync_snapshot_with_wait_timeout(
287            self.state,
288            request,
289            wait_timeout,
290            before_submit,
291            wait,
292        )?;
293        if let Err(error) = retain_reply(&reply) {
294            zeroize::Zeroize::zeroize(&mut self.state.cookie);
295            self.state.cookie = cookie.to_vec();
296            return Err(error);
297        }
298        Ok(reply)
299    }
300}
301
302impl NativeClient {
303    /// Change transport deadlines/budgets for a handle while retaining the same
304    /// account owner and admission rules. This never imports credential state.
305    pub fn with_request_options(&self, options: NativeOptions) -> Result<Self> {
306        // Reuse constructor validation without replacing the account owner.
307        let mut handle = Self::new(options)?;
308        handle.account = Some(self.owned_account()?.clone());
309        Ok(handle)
310    }
311
312    /// Execute one scoped account operation on the caller's blocking worker.
313    /// Uses the same admission, generation, storage and handoff barriers as async
314    /// operations. No executor or independent credential owner is constructed.
315    pub fn request_blocking<T>(
316        &self,
317        operation: impl FnOnce(&mut AccountRequest<'_>) -> Result<T>,
318    ) -> Result<T> {
319        self.account_request_blocking(|transport, state, _| {
320            operation(&mut AccountRequest {
321                transport,
322                state,
323                spent: false,
324            })
325        })
326    }
327
328    /// Explicit authentication renewal on an existing blocking worker. This
329    /// never retries the operation whose rejection prompted the caller to renew.
330    pub fn renew_session_blocking(&self, computer_name: &str) -> Result<()> {
331        let (exchange, state) = self
332            .owned_account()?
333            .begin()
334            .map_err(|error| error.context(NativeRequestNotSubmitted))?;
335        let exchange = Arc::new(exchange);
336        let mut transport = Self::new(self.options.clone())?;
337        let submission = exchange.clone();
338        transport.submission_guard = Some(Arc::new(move || {
339            submission
340                .check()
341                .map_err(|error| error.context(NativeRequestNotSubmitted))
342        }));
343        let accepted = transport.renew_session_snapshot(&state, computer_name)?;
344        exchange.accept_credentials(accepted)
345    }
346
347    /// As [`Self::logout`], on the caller's blocking worker. No Tokio runtime
348    /// is needed. Logout is submitted at most once and the owner stays stopped
349    /// after rejection or uncertainty.
350    pub fn logout_blocking(&self) -> Result<crate::LogoutReply> {
351        self.prepare_logout()?.submit_blocking()
352    }
353
354    /// As [`Self::shutdown`], on the caller's blocking worker. Do not call it
355    /// from inside an account request: it waits for every request to finish.
356    pub fn shutdown_blocking(&self) -> Result<()> {
357        self.owned_account()?.stop_and_drain_blocking()
358    }
359}
360
361#[cfg(test)]
362mod tests {
363    use super::*;
364
365    #[test]
366    fn scoped_requests_share_owner_and_cannot_submit_after_stop() {
367        let client = super::super::tests::client();
368        let other = client
369            .with_request_options(NativeOptions::default())
370            .unwrap();
371        other
372            .request_blocking(|request| {
373                assert_eq!(request.account().uin, 1);
374                request.admit()?;
375                request.state.cookie = vec![4];
376                Ok(())
377            })
378            .unwrap();
379        assert_eq!(client.export_account_state().unwrap().cookie, vec![4]);
380        client.stop().unwrap();
381        let entered = AtomicBool::new(false);
382        let error = other
383            .request_blocking(|_| {
384                entered.store(true, Ordering::Release);
385                Ok(())
386            })
387            .unwrap_err();
388        assert!(error.is::<NativeRequestNotSubmitted>());
389        assert!(!entered.load(Ordering::Acquire));
390    }
391
392    #[test]
393    fn scoped_context_cannot_turn_a_second_operation_into_an_unsent_retry() {
394        let client = super::super::tests::client();
395        let error = client
396            .request_blocking(|request| {
397                request.admit()?;
398                request.state.cookie = vec![7];
399                request.admit()
400            })
401            .unwrap_err();
402        assert!(!error.is::<NativeRequestNotSubmitted>());
403        assert_eq!(client.export_account_state().unwrap().cookie, vec![7]);
404        assert_eq!(client.account_status().unwrap().in_flight, 0);
405    }
406
407    #[tokio::test]
408    async fn blocking_workers_and_async_requests_share_one_response_order() {
409        let client = super::super::tests::client();
410        let old = client.clone();
411        let (ready, ready_rx) = tokio::sync::oneshot::channel();
412        let (finish, finish_rx) = std::sync::mpsc::channel();
413        let worker = tokio::task::spawn_blocking(move || {
414            old.request_blocking(|request| {
415                request.admit()?;
416                ready.send(()).unwrap();
417                finish_rx.recv()?;
418                request.state.cookie = vec![1];
419                Ok(())
420            })
421        });
422        ready_rx.await.unwrap();
423        client
424            .account_request(|_, state, _| {
425                state.cookie = vec![2];
426                Ok(())
427            })
428            .await
429            .unwrap();
430        finish.send(()).unwrap();
431        worker.await.unwrap().unwrap();
432        assert_eq!(client.export_account_state().unwrap().cookie, vec![2]);
433    }
434}