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 short_link: Arc<crate::mmtls::ShortLinkCache>,
214}
215
216struct AccountData {
217 state: Option<AccountState>,
218 revision: u64,
219 credential_generation: u64,
220 lifecycle: AccountLifecycle,
221 in_flight: usize,
222 persistence: Option<Arc<dyn AccountPersistence>>,
223}
224
225impl AccountData {
226 fn interruption(&self) -> AccountInterrupted {
228 match self.lifecycle {
229 AccountLifecycle::Transferred => AccountInterrupted::Transferred,
230 AccountLifecycle::Active | AccountLifecycle::Stopped => AccountInterrupted::Stopped,
231 }
232 }
233
234 fn ensure_active(&self, message: &'static str) -> Result<()> {
235 if self.lifecycle == AccountLifecycle::Active {
236 Ok(())
237 } else {
238 Err(self.interruption().because(message))
239 }
240 }
241}
242
243fn transferred() -> anyhow::Error {
244 AccountInterrupted::Transferred.because("Account state transferred")
245}
246
247struct Exchange {
248 account: Arc<OwnedAccount>,
249 revision: u64,
250 credential_generation: u64,
251 non_cookie: [u8; 32],
252}
253
254struct CancelOnDrop(Arc<AtomicBool>);
255
256impl Drop for CancelOnDrop {
257 fn drop(&mut self) {
258 self.0.store(true, Ordering::Release);
259 }
260}
261
262impl OwnedAccount {
263 fn lock(&self) -> Result<MutexGuard<'_, AccountData>> {
264 self.data
265 .lock()
266 .map_err(|_| anyhow::anyhow!("Account state lock poisoned"))
267 }
268
269 fn notify_changed(&self) {
271 self.changed.notify_waiters();
272 self.changed_blocking.notify_all();
273 }
274
275 fn begin(self: &Arc<Self>) -> Result<(Exchange, AccountState)> {
276 self.begin_with_terminal(false)
277 }
278
279 fn begin_with_terminal(self: &Arc<Self>, terminal: bool) -> Result<(Exchange, AccountState)> {
280 let mut data = self.lock()?;
281 if !self.authority.active.load(Ordering::Acquire) {
282 return Err(data.interruption().because("Account is stopped"));
283 }
284 data.ensure_active("Account is stopped")?;
285 let state = data.state.as_ref().ok_or_else(transferred)?.clone();
286 let non_cookie = non_cookie_digest(&state)?;
287 data.in_flight = data
288 .in_flight
289 .checked_add(1)
290 .context("Too many account requests")?;
291 let exchange = Exchange {
292 account: self.clone(),
293 revision: data.revision,
294 credential_generation: data.credential_generation,
295 non_cookie,
296 };
297 if terminal {
298 data.lifecycle = AccountLifecycle::Stopped;
299 self.authority.active.store(false, Ordering::Release);
300 }
301 drop(data);
302 if terminal {
303 self.notify_changed();
304 }
305 Ok((exchange, state))
306 }
307
308 fn stop(&self) -> Result<()> {
309 self.authority.active.store(false, Ordering::Release);
310 {
311 let mut data = self.lock()?;
312 if data.lifecycle == AccountLifecycle::Active {
313 data.lifecycle = AccountLifecycle::Stopped;
314 }
315 }
316 self.notify_changed();
317 Ok(())
318 }
319
320 async fn stopped(&self) {
321 loop {
322 let notified = self.changed.notified();
323 tokio::pin!(notified);
324 notified.as_mut().enable();
325 if !self
326 .lock()
327 .is_ok_and(|data| data.lifecycle == AccountLifecycle::Active)
328 {
329 return;
330 }
331 notified.await;
332 }
333 }
334
335 async fn stop_and_drain(&self) -> Result<()> {
336 self.stop()?;
337 self.drain_to(0).await
338 }
339
340 async fn drain_to(&self, remaining: usize) -> Result<()> {
341 loop {
342 let notified = self.changed.notified();
343 tokio::pin!(notified);
344 notified.as_mut().enable();
345 if self.lock()?.in_flight == remaining {
346 return Ok(());
347 }
348 notified.await;
349 }
350 }
351}
352
353impl OwnedAccount {
354 fn drain_to_blocking(&self, remaining: usize) -> Result<()> {
357 let mut data = self.lock()?;
358 while data.in_flight != remaining {
359 data = self
360 .changed_blocking
361 .wait(data)
362 .map_err(|_| anyhow::anyhow!("Account state lock poisoned"))?;
363 }
364 Ok(())
365 }
366
367 fn stop_and_drain_blocking(&self) -> Result<()> {
368 self.stop()?;
369 self.drain_to_blocking(0)
370 }
371}
372
373impl Exchange {
374 fn check_logout(&self) -> Result<()> {
375 let data = self.account.lock()?;
376 ensure!(
377 data.lifecycle == AccountLifecycle::Stopped && data.in_flight == 1,
378 "Logout is not the exclusive account operation"
379 );
380 let current = data.state.as_ref().ok_or_else(transferred)?;
381 ensure!(
382 data.credential_generation == self.credential_generation
383 && non_cookie_digest(current)? == self.non_cookie,
384 "Account authentication superseded logout"
385 );
386 Ok(())
387 }
388 fn check(&self) -> Result<()> {
391 let data = self.account.lock()?;
392 data.ensure_active("Account stopped during request")?;
393 let current = data.state.as_ref().ok_or_else(transferred)?;
394 if data.credential_generation != self.credential_generation
395 || non_cookie_digest(current)? != self.non_cookie
396 {
397 return Err(AccountInterrupted::CredentialsSuperseded
398 .because("Account credentials changed during request"));
399 }
400 Ok(())
401 }
402
403 fn accept_cookie(&self, returned: &AccountState) -> Result<()> {
404 returned.validate()?;
405 ensure!(
406 non_cookie_digest(returned)? == self.non_cookie,
407 "Unexpected account credential change"
408 );
409 let mut data = self.account.lock()?;
410 data.ensure_active("Account stopped during request")?;
411 let current = data.state.as_ref().ok_or_else(transferred)?;
412 if data.credential_generation != self.credential_generation
413 || non_cookie_digest(current)? != self.non_cookie
414 {
415 return Err(AccountInterrupted::CredentialsSuperseded
416 .because("Account credentials changed during request"));
417 }
418 if data.revision == self.revision && current.cookie != returned.cookie {
421 let revision = data
422 .revision
423 .checked_add(1)
424 .context("Account revision exhausted")?;
425 if let Some(storage) = &data.persistence {
426 storage
427 .persist(current, returned)
428 .map_err(|error| error.context(AccountPersistenceFailed))?;
429 }
430 data.state
431 .as_mut()
432 .ok_or_else(transferred)?
433 .cookie
434 .clone_from(&returned.cookie);
435 data.revision = revision;
436 }
437 Ok(())
438 }
439
440 fn accept_credentials(&self, returned: AccountState) -> Result<()> {
441 returned.validate()?;
442 let mut data = self.account.lock()?;
443 data.ensure_active("Account stopped during authentication")?;
444 let current = data.state.as_ref().ok_or_else(transferred)?;
445 if data.credential_generation != self.credential_generation
446 || non_cookie_digest(current)? != self.non_cookie
447 {
448 return Err(AccountInterrupted::CredentialsSuperseded
449 .because("Account authentication superseded"));
450 }
451 ensure!(
452 current.uin == returned.uin
453 && current.own_username == returned.own_username
454 && current.device.device_id == returned.device.device_id
455 && current.device.device_type == returned.device.device_type
456 && current.device.client_version == returned.device.client_version,
457 "Account authentication identity mismatch"
458 );
459 let revision = data
460 .revision
461 .checked_add(1)
462 .context("Account revision exhausted")?;
463 let generation = data
464 .credential_generation
465 .checked_add(1)
466 .context("Account credential generation exhausted")?;
467 if let Some(storage) = &data.persistence {
468 storage
469 .persist(current, &returned)
470 .map_err(|error| error.context(AccountPersistenceFailed))?;
471 }
472 data.state = Some(returned);
473 data.revision = revision;
474 data.credential_generation = generation;
475 self.account
476 .authority
477 .credential_generation
478 .store(generation, Ordering::Release);
479 Ok(())
480 }
481}
482
483impl Drop for Exchange {
484 fn drop(&mut self) {
485 let mut data = self
488 .account
489 .data
490 .lock()
491 .unwrap_or_else(|error| error.into_inner());
492 data.in_flight -= 1;
493 drop(data);
494 self.account.notify_changed();
495 }
496}
497
498fn non_cookie_digest(state: &AccountState) -> Result<[u8; 32]> {
499 let mut without_cookie = state.clone();
500 zeroize::Zeroize::zeroize(&mut without_cookie.cookie);
501 without_cookie.cookie.clear();
502 let encoded = Zeroizing::new(serde_json::to_vec(&without_cookie)?);
503 Ok(openssl::sha::sha256(&encoded))
504}
505
506impl NativeClient {
507 pub(super) fn check_snapshot_transport(&self) -> Result<()> {
508 ensure!(
509 self.account.is_none(),
510 "Explicit-state transport cannot use a bound account client"
511 );
512 Ok(())
513 }
514
515 pub(super) fn check_submission(&self) -> Result<()> {
516 if let Some(check) = &self.submission_guard {
517 check()?;
518 }
519 Ok(())
520 }
521 pub fn from_account(state: AccountState, options: NativeOptions) -> Result<Self> {
524 state.validate()?;
525 let mut client = Self::new(options)?;
526 client.account = Some(Arc::new(OwnedAccount {
527 data: Mutex::new(AccountData {
528 state: Some(state),
529 revision: 0,
530 credential_generation: 0,
531 lifecycle: AccountLifecycle::Active,
532 in_flight: 0,
533 persistence: None,
534 }),
535 changed: Notify::new(),
536 changed_blocking: Condvar::new(),
537 authority: Arc::new(Authority {
538 active: AtomicBool::new(true),
539 credential_generation: AtomicU64::new(0),
540 }),
541 components: components::AccountComponents::default(),
542 short_link: Arc::default(),
543 }));
544 Ok(client)
545 }
546
547 pub fn from_account_with_persistence(
551 state: AccountState,
552 options: NativeOptions,
553 persistence: Arc<dyn AccountPersistence>,
554 ) -> Result<Self> {
555 let client = Self::from_account(state, options)?;
556 client.owned_account()?.lock()?.persistence = Some(persistence);
557 Ok(client)
558 }
559
560 fn owned_account(&self) -> Result<&Arc<OwnedAccount>> {
561 self.account
562 .as_ref()
563 .context("Native client has no bound account")
564 }
565
566 pub fn account_status(&self) -> Result<AccountStatus> {
567 let data = self.owned_account()?.lock()?;
568 Ok(AccountStatus {
569 lifecycle: data.lifecycle,
570 revision: data.revision,
571 credential_generation: data.credential_generation,
572 in_flight: data.in_flight,
573 })
574 }
575
576 pub fn account_identity(&self) -> Result<AccountIdentity> {
577 let data = self.owned_account()?.lock()?;
578 let state = data.state.as_ref().ok_or_else(transferred)?;
579 Ok(AccountIdentity {
580 uin: state.uin,
581 own_username: state.own_username.clone(),
582 })
583 }
584
585 pub fn account_lease(&self) -> Result<AccountLease> {
586 let account = self.owned_account()?;
587 let data = account.lock()?;
588 if !account.authority.active.load(Ordering::Acquire) {
589 return Err(data.interruption().because("Account is stopped"));
590 }
591 data.ensure_active("Account is stopped")?;
592 Ok(AccountLease {
593 authority: account.authority.clone(),
594 credential_generation: data.credential_generation,
595 })
596 }
597
598 pub fn export_account_state(&self) -> Result<AccountState> {
601 self.owned_account()?
602 .lock()?
603 .state
604 .as_ref()
605 .cloned()
606 .ok_or_else(transferred)
607 }
608
609 pub async fn shutdown(&self) -> Result<()> {
612 self.owned_account()?.stop_and_drain().await
613 }
614
615 pub fn stop(&self) -> Result<()> {
618 self.owned_account()?.stop()
619 }
620
621 pub fn prepare_logout(&self) -> Result<PendingLogout> {
624 let account = self.owned_account()?;
625 let (exchange, state) = account
626 .begin_with_terminal(true)
627 .map_err(|error| error.context(NativeRequestNotSubmitted))?;
628 Ok(PendingLogout {
629 exchange: Arc::new(exchange),
630 state,
631 options: self.options.clone(),
632 })
633 }
634
635 pub async fn stopped(&self) -> Result<()> {
637 self.owned_account()?.stopped().await;
638 Ok(())
639 }
640
641 pub async fn quiesce_and_export(&self) -> Result<AccountState> {
644 let account = self.owned_account()?;
645 account.stop_and_drain().await?;
646 let mut data = account.lock()?;
647 let state = data
648 .state
649 .take()
650 .context("Account state already transferred")?;
651 data.lifecycle = AccountLifecycle::Transferred;
652 Ok(state)
653 }
654
655 async fn account_request<T, F>(&self, operation: F) -> Result<T>
656 where
657 T: Send + 'static,
658 F: FnOnce(&NativeClient, &mut AccountState, &dyn Fn() -> Result<()>) -> Result<T>
659 + Send
660 + 'static,
661 {
662 let owner = self.owned_account()?;
663 let (exchange, state) = owner
664 .begin()
665 .map_err(|error| error.context(NativeRequestNotSubmitted))?;
666 let short_link = owner.short_link.clone();
667 let options = self.options.clone();
668 let cancellation = Arc::new(AtomicBool::new(false));
669 let _cancel_on_drop = CancelOnDrop(cancellation.clone());
670 tokio::task::spawn_blocking(move || {
671 Self::execute_account_request(
672 options,
673 exchange,
674 state,
675 short_link,
676 cancellation,
677 operation,
678 )
679 })
680 .await
681 .context("Account request worker failed")?
682 }
683
684 fn account_request_blocking<T, F>(&self, operation: F) -> Result<T>
685 where
686 F: FnOnce(&NativeClient, &mut AccountState, &dyn Fn() -> Result<()>) -> Result<T>,
687 {
688 let owner = self.owned_account()?;
689 let (exchange, state) = owner
690 .begin()
691 .map_err(|error| error.context(NativeRequestNotSubmitted))?;
692 Self::execute_account_request(
693 self.options.clone(),
694 exchange,
695 state,
696 owner.short_link.clone(),
697 Arc::new(AtomicBool::new(false)),
698 operation,
699 )
700 }
701
702 fn execute_account_request<T, F>(
703 options: NativeOptions,
704 exchange: Exchange,
705 mut state: AccountState,
706 short_link: Arc<crate::mmtls::ShortLinkCache>,
707 cancellation: Arc<AtomicBool>,
708 operation: F,
709 ) -> Result<T>
710 where
711 F: FnOnce(&NativeClient, &mut AccountState, &dyn Fn() -> Result<()>) -> Result<T>,
712 {
713 let exchange = Arc::new(exchange);
714 let mut transport = NativeClient::new(options)?;
716 transport.short_link = Some(short_link);
717 let submission_exchange = exchange.clone();
718 let prior_admission = AtomicBool::new(false);
719 transport.submission_guard = Some(Arc::new(move || {
720 let check = (|| {
721 ensure!(
722 !cancellation.load(Ordering::Acquire),
723 "Account request cancelled before submission"
724 );
725 submission_exchange.check()
726 })();
727 match check {
728 Ok(()) => {
729 prior_admission.store(true, Ordering::Release);
730 Ok(())
731 }
732 Err(error) if !prior_admission.load(Ordering::Acquire) => {
733 Err(error.context(NativeRequestNotSubmitted))
734 }
735 Err(error) => Err(error),
738 }
739 }));
740 let result = operation(&transport, &mut state, &|| transport.check_submission());
741 let accepted = exchange.accept_cookie(&state);
744 match result {
745 Ok(value) => {
746 accepted?;
747 Ok(value)
748 }
749 Err(error) => match accepted {
750 Ok(()) => Err(error),
751 Err(account_error) => Err(error.context(account_error)),
752 },
753 }
754 }
755}
756
757#[path = "account_request.rs"]
758mod request;
759pub use request::AccountRequest;
760
761#[path = "account_push.rs"]
762mod push;
763pub use push::AccountPushConnection;
764
765#[path = "account_operations.rs"]
766mod operations;
767
768async fn wait_for_poll<R, C, S>(reply: R, cancellation: C, stopped: S) -> Result<Vec<u8>>
769where
770 R: Future<Output = Result<Vec<u8>>>,
771 C: Future<Output = ()>,
772 S: Future<Output = ()>,
773{
774 tokio::select! {
775 biased;
776 () = stopped => Err(crate::calls::host_transport::CallLiveSyncInterrupted.into()),
777 () = cancellation => Err(crate::calls::host_transport::CallLiveSyncInterrupted.into()),
778 result = reply => result,
779 }
780}
781
782#[cfg(test)]
783#[path = "account_tests.rs"]
784mod tests;