1use super::{AccountState, NativeClient, NativeOptions};
4use crate::errors::AccountInterrupted;
5use anyhow::{ensure, Context, Result};
6use serde::{Deserialize, Serialize};
7use std::{
8 future::Future,
9 sync::{
10 atomic::{AtomicBool, AtomicU64, Ordering},
11 Arc, Condvar, Mutex, MutexGuard,
12 },
13 time::Duration,
14};
15use tokio::sync::Notify;
16use zeroize::Zeroizing;
17
18#[path = "account_components.rs"]
19mod components;
20
21#[derive(Debug)]
24pub struct NativeRequestNotSubmitted;
25
26impl std::fmt::Display for NativeRequestNotSubmitted {
27 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28 f.write_str("Native request stopped before business submission")
29 }
30}
31
32impl std::error::Error for NativeRequestNotSubmitted {}
33
34#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36pub enum AccountLifecycle {
37 Active,
38 Stopped,
39 Transferred,
40}
41
42#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(rename_all = "camelCase")]
46pub struct AccountStatus {
47 pub lifecycle: AccountLifecycle,
48 pub revision: u64,
49 pub credential_generation: u64,
50 pub in_flight: usize,
51}
52
53#[derive(Clone, Debug, PartialEq, Eq)]
54pub struct AccountIdentity {
55 pub uin: u32,
56 pub own_username: String,
57}
58
59#[derive(Clone)]
63pub struct AccountLease {
64 authority: Arc<Authority>,
65 credential_generation: u64,
66}
67struct Authority {
68 active: AtomicBool,
69 credential_generation: AtomicU64,
70}
71impl AccountLease {
72 pub fn current(&self) -> bool {
73 self.authority.active.load(Ordering::Acquire)
74 && self.authority.credential_generation.load(Ordering::Acquire)
75 == self.credential_generation
76 }
77}
78
79#[derive(Clone, Debug)]
82pub struct TextSendOptions {
83 pub created_at: u32,
84 pub client_message_id: u32,
85 pub source: Option<String>,
86}
87
88pub trait AccountPersistence: Send + Sync {
93 fn persist(&self, previous: &AccountState, accepted: &AccountState) -> Result<()>;
94}
95
96#[derive(Debug)]
99pub struct AccountPersistenceFailed;
100impl std::fmt::Display for AccountPersistenceFailed {
101 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102 f.write_str("Accepted account update could not be persisted")
103 }
104}
105impl std::error::Error for AccountPersistenceFailed {}
106
107pub struct PendingLogout {
112 exchange: Arc<Exchange>,
113 state: AccountState,
114 options: NativeOptions,
115}
116
117impl PendingLogout {
118 pub async fn submit(self) -> Result<super::LogoutReply> {
121 self.submit_guarded(|| Ok(())).await
122 }
123
124 pub async fn submit_guarded<F>(self, before_submit: F) -> Result<super::LogoutReply>
128 where
129 F: FnOnce() -> Result<()> + Send + 'static,
130 {
131 self.exchange.account.drain_to(1).await?;
132 let cancellation = Arc::new(AtomicBool::new(false));
133 let _cancel_on_drop = CancelOnDrop(cancellation.clone());
134 tokio::task::spawn_blocking(move || self.submit_on_worker(cancellation, before_submit))
135 .await
136 .context("Account logout worker failed")?
137 }
138
139 pub fn submit_blocking(self) -> Result<super::LogoutReply> {
143 self.submit_guarded_blocking(|| Ok(()))
144 }
145
146 pub fn submit_guarded_blocking<F>(self, before_submit: F) -> Result<super::LogoutReply>
150 where
151 F: FnOnce() -> Result<()> + Send + 'static,
152 {
153 self.exchange.account.drain_to_blocking(1)?;
154 self.submit_on_worker(Arc::new(AtomicBool::new(false)), before_submit)
155 }
156
157 fn submit_on_worker<F>(
158 self,
159 cancellation: Arc<AtomicBool>,
160 before_submit: F,
161 ) -> Result<super::LogoutReply>
162 where
163 F: FnOnce() -> Result<()> + Send + 'static,
164 {
165 let Self {
166 exchange,
167 mut state,
168 options,
169 } = self;
170 let mut transport = NativeClient::new(options)?;
171 transport.submission_guard = Some(logout_guard(exchange, cancellation, before_submit));
172 transport.logout_snapshot(&mut state)
173 }
174}
175
176fn logout_guard<F>(
179 exchange: Arc<Exchange>,
180 cancellation: Arc<AtomicBool>,
181 before_submit: F,
182) -> Arc<dyn Fn() -> Result<()> + Send + Sync>
183where
184 F: FnOnce() -> Result<()> + Send + 'static,
185{
186 let before_submit = Mutex::new(Some(before_submit));
187 Arc::new(move || {
188 let check = (|| {
189 ensure!(
190 !cancellation.load(Ordering::Acquire),
191 "Account logout cancelled before submission"
192 );
193 exchange.check_logout()
194 })();
195 check.map_err(|error| error.context(NativeRequestNotSubmitted))?;
196 let guard = before_submit
197 .lock()
198 .map_err(|_| anyhow::anyhow!("Logout guard unavailable"))?
199 .take()
200 .context("Logout already submitted")?;
201 guard().map_err(|error| error.context(NativeRequestNotSubmitted))
202 })
203}
204
205pub(super) struct OwnedAccount {
206 data: Mutex<AccountData>,
207 changed: Notify,
208 changed_blocking: Condvar,
210 authority: Arc<Authority>,
211 components: components::AccountComponents,
212}
213
214struct AccountData {
215 state: Option<AccountState>,
216 revision: u64,
217 credential_generation: u64,
218 lifecycle: AccountLifecycle,
219 in_flight: usize,
220 persistence: Option<Arc<dyn AccountPersistence>>,
221}
222
223impl AccountData {
224 fn interruption(&self) -> AccountInterrupted {
226 match self.lifecycle {
227 AccountLifecycle::Transferred => AccountInterrupted::Transferred,
228 AccountLifecycle::Active | AccountLifecycle::Stopped => AccountInterrupted::Stopped,
229 }
230 }
231
232 fn ensure_active(&self, message: &'static str) -> Result<()> {
233 if self.lifecycle == AccountLifecycle::Active {
234 Ok(())
235 } else {
236 Err(self.interruption().because(message))
237 }
238 }
239}
240
241fn transferred() -> anyhow::Error {
242 AccountInterrupted::Transferred.because("Account state transferred")
243}
244
245struct Exchange {
246 account: Arc<OwnedAccount>,
247 revision: u64,
248 credential_generation: u64,
249 non_cookie: [u8; 32],
250}
251
252struct CancelOnDrop(Arc<AtomicBool>);
253
254impl Drop for CancelOnDrop {
255 fn drop(&mut self) {
256 self.0.store(true, Ordering::Release);
257 }
258}
259
260impl OwnedAccount {
261 fn lock(&self) -> Result<MutexGuard<'_, AccountData>> {
262 self.data
263 .lock()
264 .map_err(|_| anyhow::anyhow!("Account state lock poisoned"))
265 }
266
267 fn notify_changed(&self) {
269 self.changed.notify_waiters();
270 self.changed_blocking.notify_all();
271 }
272
273 fn begin(self: &Arc<Self>) -> Result<(Exchange, AccountState)> {
274 self.begin_with_terminal(false)
275 }
276
277 fn begin_with_terminal(self: &Arc<Self>, terminal: bool) -> Result<(Exchange, AccountState)> {
278 let mut data = self.lock()?;
279 if !self.authority.active.load(Ordering::Acquire) {
280 return Err(data.interruption().because("Account is stopped"));
281 }
282 data.ensure_active("Account is stopped")?;
283 let state = data.state.as_ref().ok_or_else(transferred)?.clone();
284 let non_cookie = non_cookie_digest(&state)?;
285 data.in_flight = data
286 .in_flight
287 .checked_add(1)
288 .context("Too many account requests")?;
289 let exchange = Exchange {
290 account: self.clone(),
291 revision: data.revision,
292 credential_generation: data.credential_generation,
293 non_cookie,
294 };
295 if terminal {
296 data.lifecycle = AccountLifecycle::Stopped;
297 self.authority.active.store(false, Ordering::Release);
298 }
299 drop(data);
300 if terminal {
301 self.notify_changed();
302 }
303 Ok((exchange, state))
304 }
305
306 fn stop(&self) -> Result<()> {
307 self.authority.active.store(false, Ordering::Release);
308 {
309 let mut data = self.lock()?;
310 if data.lifecycle == AccountLifecycle::Active {
311 data.lifecycle = AccountLifecycle::Stopped;
312 }
313 }
314 self.notify_changed();
315 Ok(())
316 }
317
318 async fn stopped(&self) {
319 loop {
320 let notified = self.changed.notified();
321 tokio::pin!(notified);
322 notified.as_mut().enable();
323 if !self
324 .lock()
325 .is_ok_and(|data| data.lifecycle == AccountLifecycle::Active)
326 {
327 return;
328 }
329 notified.await;
330 }
331 }
332
333 async fn stop_and_drain(&self) -> Result<()> {
334 self.stop()?;
335 self.drain_to(0).await
336 }
337
338 async fn drain_to(&self, remaining: usize) -> Result<()> {
339 loop {
340 let notified = self.changed.notified();
341 tokio::pin!(notified);
342 notified.as_mut().enable();
343 if self.lock()?.in_flight == remaining {
344 return Ok(());
345 }
346 notified.await;
347 }
348 }
349}
350
351impl OwnedAccount {
352 fn drain_to_blocking(&self, remaining: usize) -> Result<()> {
355 let mut data = self.lock()?;
356 while data.in_flight != remaining {
357 data = self
358 .changed_blocking
359 .wait(data)
360 .map_err(|_| anyhow::anyhow!("Account state lock poisoned"))?;
361 }
362 Ok(())
363 }
364
365 fn stop_and_drain_blocking(&self) -> Result<()> {
366 self.stop()?;
367 self.drain_to_blocking(0)
368 }
369}
370
371impl Exchange {
372 fn check_logout(&self) -> Result<()> {
373 let data = self.account.lock()?;
374 ensure!(
375 data.lifecycle == AccountLifecycle::Stopped && data.in_flight == 1,
376 "Logout is not the exclusive account operation"
377 );
378 let current = data.state.as_ref().ok_or_else(transferred)?;
379 ensure!(
380 data.credential_generation == self.credential_generation
381 && non_cookie_digest(current)? == self.non_cookie,
382 "Account authentication superseded logout"
383 );
384 Ok(())
385 }
386 fn check(&self) -> Result<()> {
389 let data = self.account.lock()?;
390 data.ensure_active("Account stopped during request")?;
391 let current = data.state.as_ref().ok_or_else(transferred)?;
392 if data.credential_generation != self.credential_generation
393 || non_cookie_digest(current)? != self.non_cookie
394 {
395 return Err(AccountInterrupted::CredentialsSuperseded
396 .because("Account credentials changed during request"));
397 }
398 Ok(())
399 }
400
401 fn accept_cookie(&self, returned: &AccountState) -> Result<()> {
402 returned.validate()?;
403 ensure!(
404 non_cookie_digest(returned)? == self.non_cookie,
405 "Unexpected account credential change"
406 );
407 let mut data = self.account.lock()?;
408 data.ensure_active("Account stopped during request")?;
409 let current = data.state.as_ref().ok_or_else(transferred)?;
410 if data.credential_generation != self.credential_generation
411 || non_cookie_digest(current)? != self.non_cookie
412 {
413 return Err(AccountInterrupted::CredentialsSuperseded
414 .because("Account credentials changed during request"));
415 }
416 if data.revision == self.revision && current.cookie != returned.cookie {
419 let revision = data
420 .revision
421 .checked_add(1)
422 .context("Account revision exhausted")?;
423 if let Some(storage) = &data.persistence {
424 storage
425 .persist(current, returned)
426 .map_err(|error| error.context(AccountPersistenceFailed))?;
427 }
428 data.state
429 .as_mut()
430 .ok_or_else(transferred)?
431 .cookie
432 .clone_from(&returned.cookie);
433 data.revision = revision;
434 }
435 Ok(())
436 }
437
438 fn accept_credentials(&self, returned: AccountState) -> Result<()> {
439 returned.validate()?;
440 let mut data = self.account.lock()?;
441 data.ensure_active("Account stopped during authentication")?;
442 let current = data.state.as_ref().ok_or_else(transferred)?;
443 if data.credential_generation != self.credential_generation
444 || non_cookie_digest(current)? != self.non_cookie
445 {
446 return Err(AccountInterrupted::CredentialsSuperseded
447 .because("Account authentication superseded"));
448 }
449 ensure!(
450 current.uin == returned.uin
451 && current.own_username == returned.own_username
452 && current.device.device_id == returned.device.device_id
453 && current.device.device_type == returned.device.device_type
454 && current.device.client_version == returned.device.client_version,
455 "Account authentication identity mismatch"
456 );
457 let revision = data
458 .revision
459 .checked_add(1)
460 .context("Account revision exhausted")?;
461 let generation = data
462 .credential_generation
463 .checked_add(1)
464 .context("Account credential generation exhausted")?;
465 if let Some(storage) = &data.persistence {
466 storage
467 .persist(current, &returned)
468 .map_err(|error| error.context(AccountPersistenceFailed))?;
469 }
470 data.state = Some(returned);
471 data.revision = revision;
472 data.credential_generation = generation;
473 self.account
474 .authority
475 .credential_generation
476 .store(generation, Ordering::Release);
477 Ok(())
478 }
479}
480
481impl Drop for Exchange {
482 fn drop(&mut self) {
483 let mut data = self
486 .account
487 .data
488 .lock()
489 .unwrap_or_else(|error| error.into_inner());
490 data.in_flight -= 1;
491 drop(data);
492 self.account.notify_changed();
493 }
494}
495
496fn non_cookie_digest(state: &AccountState) -> Result<[u8; 32]> {
497 let mut without_cookie = state.clone();
498 zeroize::Zeroize::zeroize(&mut without_cookie.cookie);
499 without_cookie.cookie.clear();
500 let encoded = Zeroizing::new(serde_json::to_vec(&without_cookie)?);
501 Ok(openssl::sha::sha256(&encoded))
502}
503
504impl NativeClient {
505 pub(super) fn check_snapshot_transport(&self) -> Result<()> {
506 ensure!(
507 self.account.is_none(),
508 "Explicit-state transport cannot use a bound account client"
509 );
510 Ok(())
511 }
512
513 pub(super) fn check_submission(&self) -> Result<()> {
514 if let Some(check) = &self.submission_guard {
515 check()?;
516 }
517 Ok(())
518 }
519 pub fn from_account(state: AccountState, options: NativeOptions) -> Result<Self> {
522 state.validate()?;
523 let mut client = Self::new(options)?;
524 client.account = Some(Arc::new(OwnedAccount {
525 data: Mutex::new(AccountData {
526 state: Some(state),
527 revision: 0,
528 credential_generation: 0,
529 lifecycle: AccountLifecycle::Active,
530 in_flight: 0,
531 persistence: None,
532 }),
533 changed: Notify::new(),
534 changed_blocking: Condvar::new(),
535 authority: Arc::new(Authority {
536 active: AtomicBool::new(true),
537 credential_generation: AtomicU64::new(0),
538 }),
539 components: components::AccountComponents::default(),
540 }));
541 Ok(client)
542 }
543
544 pub fn from_account_with_persistence(
548 state: AccountState,
549 options: NativeOptions,
550 persistence: Arc<dyn AccountPersistence>,
551 ) -> Result<Self> {
552 let client = Self::from_account(state, options)?;
553 client.owned_account()?.lock()?.persistence = Some(persistence);
554 Ok(client)
555 }
556
557 fn owned_account(&self) -> Result<&Arc<OwnedAccount>> {
558 self.account
559 .as_ref()
560 .context("Native client has no bound account")
561 }
562
563 pub fn account_status(&self) -> Result<AccountStatus> {
564 let data = self.owned_account()?.lock()?;
565 Ok(AccountStatus {
566 lifecycle: data.lifecycle,
567 revision: data.revision,
568 credential_generation: data.credential_generation,
569 in_flight: data.in_flight,
570 })
571 }
572
573 pub fn account_identity(&self) -> Result<AccountIdentity> {
574 let data = self.owned_account()?.lock()?;
575 let state = data.state.as_ref().ok_or_else(transferred)?;
576 Ok(AccountIdentity {
577 uin: state.uin,
578 own_username: state.own_username.clone(),
579 })
580 }
581
582 pub fn account_lease(&self) -> Result<AccountLease> {
583 let account = self.owned_account()?;
584 let data = account.lock()?;
585 if !account.authority.active.load(Ordering::Acquire) {
586 return Err(data.interruption().because("Account is stopped"));
587 }
588 data.ensure_active("Account is stopped")?;
589 Ok(AccountLease {
590 authority: account.authority.clone(),
591 credential_generation: data.credential_generation,
592 })
593 }
594
595 pub fn export_account_state(&self) -> Result<AccountState> {
598 self.owned_account()?
599 .lock()?
600 .state
601 .as_ref()
602 .cloned()
603 .ok_or_else(transferred)
604 }
605
606 pub async fn shutdown(&self) -> Result<()> {
609 self.owned_account()?.stop_and_drain().await
610 }
611
612 pub fn stop(&self) -> Result<()> {
615 self.owned_account()?.stop()
616 }
617
618 pub fn prepare_logout(&self) -> Result<PendingLogout> {
621 let account = self.owned_account()?;
622 let (exchange, state) = account
623 .begin_with_terminal(true)
624 .map_err(|error| error.context(NativeRequestNotSubmitted))?;
625 Ok(PendingLogout {
626 exchange: Arc::new(exchange),
627 state,
628 options: self.options.clone(),
629 })
630 }
631
632 pub async fn stopped(&self) -> Result<()> {
634 self.owned_account()?.stopped().await;
635 Ok(())
636 }
637
638 pub async fn quiesce_and_export(&self) -> Result<AccountState> {
641 let account = self.owned_account()?;
642 account.stop_and_drain().await?;
643 let mut data = account.lock()?;
644 let state = data
645 .state
646 .take()
647 .context("Account state already transferred")?;
648 data.lifecycle = AccountLifecycle::Transferred;
649 Ok(state)
650 }
651
652 async fn account_request<T, F>(&self, operation: F) -> Result<T>
653 where
654 T: Send + 'static,
655 F: FnOnce(&NativeClient, &mut AccountState, &dyn Fn() -> Result<()>) -> Result<T>
656 + Send
657 + 'static,
658 {
659 let (exchange, state) = self
660 .owned_account()?
661 .begin()
662 .map_err(|error| error.context(NativeRequestNotSubmitted))?;
663 let options = self.options.clone();
664 let cancellation = Arc::new(AtomicBool::new(false));
665 let _cancel_on_drop = CancelOnDrop(cancellation.clone());
666 tokio::task::spawn_blocking(move || {
667 Self::execute_account_request(options, exchange, state, cancellation, operation)
668 })
669 .await
670 .context("Account request worker failed")?
671 }
672
673 fn account_request_blocking<T, F>(&self, operation: F) -> Result<T>
674 where
675 F: FnOnce(&NativeClient, &mut AccountState, &dyn Fn() -> Result<()>) -> Result<T>,
676 {
677 let (exchange, state) = self
678 .owned_account()?
679 .begin()
680 .map_err(|error| error.context(NativeRequestNotSubmitted))?;
681 Self::execute_account_request(
682 self.options.clone(),
683 exchange,
684 state,
685 Arc::new(AtomicBool::new(false)),
686 operation,
687 )
688 }
689
690 fn execute_account_request<T, F>(
691 options: NativeOptions,
692 exchange: Exchange,
693 mut state: AccountState,
694 cancellation: Arc<AtomicBool>,
695 operation: F,
696 ) -> Result<T>
697 where
698 F: FnOnce(&NativeClient, &mut AccountState, &dyn Fn() -> Result<()>) -> Result<T>,
699 {
700 let exchange = Arc::new(exchange);
701 let mut transport = NativeClient::new(options)?;
703 let submission_exchange = exchange.clone();
704 let prior_admission = AtomicBool::new(false);
705 transport.submission_guard = Some(Arc::new(move || {
706 let check = (|| {
707 ensure!(
708 !cancellation.load(Ordering::Acquire),
709 "Account request cancelled before submission"
710 );
711 submission_exchange.check()
712 })();
713 match check {
714 Ok(()) => {
715 prior_admission.store(true, Ordering::Release);
716 Ok(())
717 }
718 Err(error) if !prior_admission.load(Ordering::Acquire) => {
719 Err(error.context(NativeRequestNotSubmitted))
720 }
721 Err(error) => Err(error),
724 }
725 }));
726 let result = operation(&transport, &mut state, &|| transport.check_submission());
727 let accepted = exchange.accept_cookie(&state);
730 match result {
731 Ok(value) => {
732 accepted?;
733 Ok(value)
734 }
735 Err(error) => match accepted {
736 Ok(()) => Err(error),
737 Err(account_error) => Err(error.context(account_error)),
738 },
739 }
740 }
741}
742
743#[path = "account_request.rs"]
744mod request;
745pub use request::AccountRequest;
746
747#[path = "account_push.rs"]
748mod push;
749pub use push::AccountPushConnection;
750
751#[path = "account_operations.rs"]
752mod operations;
753
754async fn wait_for_poll<R, C, S>(reply: R, cancellation: C, stopped: S) -> Result<Vec<u8>>
755where
756 R: Future<Output = Result<Vec<u8>>>,
757 C: Future<Output = ()>,
758 S: Future<Output = ()>,
759{
760 tokio::select! {
761 biased;
762 () = stopped => Err(crate::calls::host_transport::CallLiveSyncInterrupted.into()),
763 () = cancellation => Err(crate::calls::host_transport::CallLiveSyncInterrupted.into()),
764 result = reply => result,
765 }
766}
767
768#[cfg(test)]
769#[path = "account_tests.rs"]
770mod tests;