use super::{AccountState, NativeClient, NativeOptions};
use crate::errors::AccountInterrupted;
use anyhow::{ensure, Context, Result};
use serde::{Deserialize, Serialize};
use std::{
future::Future,
sync::{
atomic::{AtomicBool, AtomicU64, Ordering},
Arc, Condvar, Mutex, MutexGuard,
},
time::Duration,
};
use tokio::sync::Notify;
use zeroize::Zeroizing;
#[path = "account_components.rs"]
mod components;
#[derive(Debug)]
pub struct NativeRequestNotSubmitted;
impl std::fmt::Display for NativeRequestNotSubmitted {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Native request stopped before business submission")
}
}
impl std::error::Error for NativeRequestNotSubmitted {}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AccountLifecycle {
Active,
Stopped,
Transferred,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountStatus {
pub lifecycle: AccountLifecycle,
pub revision: u64,
pub credential_generation: u64,
pub in_flight: usize,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AccountIdentity {
pub uin: u32,
pub own_username: String,
}
#[derive(Clone)]
pub struct AccountLease {
authority: Arc<Authority>,
credential_generation: u64,
}
struct Authority {
active: AtomicBool,
credential_generation: AtomicU64,
}
impl AccountLease {
pub fn current(&self) -> bool {
self.authority.active.load(Ordering::Acquire)
&& self.authority.credential_generation.load(Ordering::Acquire)
== self.credential_generation
}
}
#[derive(Clone, Debug)]
pub struct TextSendOptions {
pub created_at: u32,
pub client_message_id: u32,
pub source: Option<String>,
}
pub trait AccountPersistence: Send + Sync {
fn persist(&self, previous: &AccountState, accepted: &AccountState) -> Result<()>;
}
#[derive(Debug)]
pub struct AccountPersistenceFailed;
impl std::fmt::Display for AccountPersistenceFailed {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Accepted account update could not be persisted")
}
}
impl std::error::Error for AccountPersistenceFailed {}
pub struct PendingLogout {
exchange: Arc<Exchange>,
state: AccountState,
options: NativeOptions,
}
impl PendingLogout {
pub async fn submit(self) -> Result<super::LogoutReply> {
self.submit_guarded(|| Ok(())).await
}
pub async fn submit_guarded<F>(self, before_submit: F) -> Result<super::LogoutReply>
where
F: FnOnce() -> Result<()> + Send + 'static,
{
self.exchange.account.drain_to(1).await?;
let cancellation = Arc::new(AtomicBool::new(false));
let _cancel_on_drop = CancelOnDrop(cancellation.clone());
tokio::task::spawn_blocking(move || self.submit_on_worker(cancellation, before_submit))
.await
.context("Account logout worker failed")?
}
pub fn submit_blocking(self) -> Result<super::LogoutReply> {
self.submit_guarded_blocking(|| Ok(()))
}
pub fn submit_guarded_blocking<F>(self, before_submit: F) -> Result<super::LogoutReply>
where
F: FnOnce() -> Result<()> + Send + 'static,
{
self.exchange.account.drain_to_blocking(1)?;
self.submit_on_worker(Arc::new(AtomicBool::new(false)), before_submit)
}
fn submit_on_worker<F>(
self,
cancellation: Arc<AtomicBool>,
before_submit: F,
) -> Result<super::LogoutReply>
where
F: FnOnce() -> Result<()> + Send + 'static,
{
let Self {
exchange,
mut state,
options,
} = self;
let mut transport = NativeClient::new(options)?;
transport.submission_guard = Some(logout_guard(exchange, cancellation, before_submit));
transport.logout_snapshot(&mut state)
}
}
fn logout_guard<F>(
exchange: Arc<Exchange>,
cancellation: Arc<AtomicBool>,
before_submit: F,
) -> Arc<dyn Fn() -> Result<()> + Send + Sync>
where
F: FnOnce() -> Result<()> + Send + 'static,
{
let before_submit = Mutex::new(Some(before_submit));
Arc::new(move || {
let check = (|| {
ensure!(
!cancellation.load(Ordering::Acquire),
"Account logout cancelled before submission"
);
exchange.check_logout()
})();
check.map_err(|error| error.context(NativeRequestNotSubmitted))?;
let guard = before_submit
.lock()
.map_err(|_| anyhow::anyhow!("Logout guard unavailable"))?
.take()
.context("Logout already submitted")?;
guard().map_err(|error| error.context(NativeRequestNotSubmitted))
})
}
pub(super) struct OwnedAccount {
data: Mutex<AccountData>,
changed: Notify,
changed_blocking: Condvar,
authority: Arc<Authority>,
components: components::AccountComponents,
short_link: Arc<crate::mmtls::ShortLinkCache>,
}
struct AccountData {
state: Option<AccountState>,
revision: u64,
credential_generation: u64,
lifecycle: AccountLifecycle,
in_flight: usize,
persistence: Option<Arc<dyn AccountPersistence>>,
}
impl AccountData {
fn interruption(&self) -> AccountInterrupted {
match self.lifecycle {
AccountLifecycle::Transferred => AccountInterrupted::Transferred,
AccountLifecycle::Active | AccountLifecycle::Stopped => AccountInterrupted::Stopped,
}
}
fn ensure_active(&self, message: &'static str) -> Result<()> {
if self.lifecycle == AccountLifecycle::Active {
Ok(())
} else {
Err(self.interruption().because(message))
}
}
}
fn transferred() -> anyhow::Error {
AccountInterrupted::Transferred.because("Account state transferred")
}
struct Exchange {
account: Arc<OwnedAccount>,
revision: u64,
credential_generation: u64,
non_cookie: [u8; 32],
}
struct CancelOnDrop(Arc<AtomicBool>);
impl Drop for CancelOnDrop {
fn drop(&mut self) {
self.0.store(true, Ordering::Release);
}
}
impl OwnedAccount {
fn lock(&self) -> Result<MutexGuard<'_, AccountData>> {
self.data
.lock()
.map_err(|_| anyhow::anyhow!("Account state lock poisoned"))
}
fn notify_changed(&self) {
self.changed.notify_waiters();
self.changed_blocking.notify_all();
}
fn begin(self: &Arc<Self>) -> Result<(Exchange, AccountState)> {
self.begin_with_terminal(false)
}
fn begin_with_terminal(self: &Arc<Self>, terminal: bool) -> Result<(Exchange, AccountState)> {
let mut data = self.lock()?;
if !self.authority.active.load(Ordering::Acquire) {
return Err(data.interruption().because("Account is stopped"));
}
data.ensure_active("Account is stopped")?;
let state = data.state.as_ref().ok_or_else(transferred)?.clone();
let non_cookie = non_cookie_digest(&state)?;
data.in_flight = data
.in_flight
.checked_add(1)
.context("Too many account requests")?;
let exchange = Exchange {
account: self.clone(),
revision: data.revision,
credential_generation: data.credential_generation,
non_cookie,
};
if terminal {
data.lifecycle = AccountLifecycle::Stopped;
self.authority.active.store(false, Ordering::Release);
}
drop(data);
if terminal {
self.notify_changed();
}
Ok((exchange, state))
}
fn stop(&self) -> Result<()> {
self.authority.active.store(false, Ordering::Release);
{
let mut data = self.lock()?;
if data.lifecycle == AccountLifecycle::Active {
data.lifecycle = AccountLifecycle::Stopped;
}
}
self.notify_changed();
Ok(())
}
async fn stopped(&self) {
loop {
let notified = self.changed.notified();
tokio::pin!(notified);
notified.as_mut().enable();
if !self
.lock()
.is_ok_and(|data| data.lifecycle == AccountLifecycle::Active)
{
return;
}
notified.await;
}
}
async fn stop_and_drain(&self) -> Result<()> {
self.stop()?;
self.drain_to(0).await
}
async fn drain_to(&self, remaining: usize) -> Result<()> {
loop {
let notified = self.changed.notified();
tokio::pin!(notified);
notified.as_mut().enable();
if self.lock()?.in_flight == remaining {
return Ok(());
}
notified.await;
}
}
}
impl OwnedAccount {
fn drain_to_blocking(&self, remaining: usize) -> Result<()> {
let mut data = self.lock()?;
while data.in_flight != remaining {
data = self
.changed_blocking
.wait(data)
.map_err(|_| anyhow::anyhow!("Account state lock poisoned"))?;
}
Ok(())
}
fn stop_and_drain_blocking(&self) -> Result<()> {
self.stop()?;
self.drain_to_blocking(0)
}
}
impl Exchange {
fn check_logout(&self) -> Result<()> {
let data = self.account.lock()?;
ensure!(
data.lifecycle == AccountLifecycle::Stopped && data.in_flight == 1,
"Logout is not the exclusive account operation"
);
let current = data.state.as_ref().ok_or_else(transferred)?;
ensure!(
data.credential_generation == self.credential_generation
&& non_cookie_digest(current)? == self.non_cookie,
"Account authentication superseded logout"
);
Ok(())
}
fn check(&self) -> Result<()> {
let data = self.account.lock()?;
data.ensure_active("Account stopped during request")?;
let current = data.state.as_ref().ok_or_else(transferred)?;
if data.credential_generation != self.credential_generation
|| non_cookie_digest(current)? != self.non_cookie
{
return Err(AccountInterrupted::CredentialsSuperseded
.because("Account credentials changed during request"));
}
Ok(())
}
fn accept_cookie(&self, returned: &AccountState) -> Result<()> {
returned.validate()?;
ensure!(
non_cookie_digest(returned)? == self.non_cookie,
"Unexpected account credential change"
);
let mut data = self.account.lock()?;
data.ensure_active("Account stopped during request")?;
let current = data.state.as_ref().ok_or_else(transferred)?;
if data.credential_generation != self.credential_generation
|| non_cookie_digest(current)? != self.non_cookie
{
return Err(AccountInterrupted::CredentialsSuperseded
.because("Account credentials changed during request"));
}
if data.revision == self.revision && current.cookie != returned.cookie {
let revision = data
.revision
.checked_add(1)
.context("Account revision exhausted")?;
if let Some(storage) = &data.persistence {
storage
.persist(current, returned)
.map_err(|error| error.context(AccountPersistenceFailed))?;
}
data.state
.as_mut()
.ok_or_else(transferred)?
.cookie
.clone_from(&returned.cookie);
data.revision = revision;
}
Ok(())
}
fn accept_credentials(&self, returned: AccountState) -> Result<()> {
returned.validate()?;
let mut data = self.account.lock()?;
data.ensure_active("Account stopped during authentication")?;
let current = data.state.as_ref().ok_or_else(transferred)?;
if data.credential_generation != self.credential_generation
|| non_cookie_digest(current)? != self.non_cookie
{
return Err(AccountInterrupted::CredentialsSuperseded
.because("Account authentication superseded"));
}
ensure!(
current.uin == returned.uin
&& current.own_username == returned.own_username
&& current.device.device_id == returned.device.device_id
&& current.device.device_type == returned.device.device_type
&& current.device.client_version == returned.device.client_version,
"Account authentication identity mismatch"
);
let revision = data
.revision
.checked_add(1)
.context("Account revision exhausted")?;
let generation = data
.credential_generation
.checked_add(1)
.context("Account credential generation exhausted")?;
if let Some(storage) = &data.persistence {
storage
.persist(current, &returned)
.map_err(|error| error.context(AccountPersistenceFailed))?;
}
data.state = Some(returned);
data.revision = revision;
data.credential_generation = generation;
self.account
.authority
.credential_generation
.store(generation, Ordering::Release);
Ok(())
}
}
impl Drop for Exchange {
fn drop(&mut self) {
let mut data = self
.account
.data
.lock()
.unwrap_or_else(|error| error.into_inner());
data.in_flight -= 1;
drop(data);
self.account.notify_changed();
}
}
fn non_cookie_digest(state: &AccountState) -> Result<[u8; 32]> {
let mut without_cookie = state.clone();
zeroize::Zeroize::zeroize(&mut without_cookie.cookie);
without_cookie.cookie.clear();
let encoded = Zeroizing::new(serde_json::to_vec(&without_cookie)?);
Ok(openssl::sha::sha256(&encoded))
}
impl NativeClient {
pub(super) fn check_snapshot_transport(&self) -> Result<()> {
ensure!(
self.account.is_none(),
"Explicit-state transport cannot use a bound account client"
);
Ok(())
}
pub(super) fn check_submission(&self) -> Result<()> {
if let Some(check) = &self.submission_guard {
check()?;
}
Ok(())
}
pub fn from_account(state: AccountState, options: NativeOptions) -> Result<Self> {
state.validate()?;
let mut client = Self::new(options)?;
client.account = Some(Arc::new(OwnedAccount {
data: Mutex::new(AccountData {
state: Some(state),
revision: 0,
credential_generation: 0,
lifecycle: AccountLifecycle::Active,
in_flight: 0,
persistence: None,
}),
changed: Notify::new(),
changed_blocking: Condvar::new(),
authority: Arc::new(Authority {
active: AtomicBool::new(true),
credential_generation: AtomicU64::new(0),
}),
components: components::AccountComponents::default(),
short_link: Arc::default(),
}));
Ok(client)
}
pub fn from_account_with_persistence(
state: AccountState,
options: NativeOptions,
persistence: Arc<dyn AccountPersistence>,
) -> Result<Self> {
let client = Self::from_account(state, options)?;
client.owned_account()?.lock()?.persistence = Some(persistence);
Ok(client)
}
fn owned_account(&self) -> Result<&Arc<OwnedAccount>> {
self.account
.as_ref()
.context("Native client has no bound account")
}
pub fn account_status(&self) -> Result<AccountStatus> {
let data = self.owned_account()?.lock()?;
Ok(AccountStatus {
lifecycle: data.lifecycle,
revision: data.revision,
credential_generation: data.credential_generation,
in_flight: data.in_flight,
})
}
pub fn account_identity(&self) -> Result<AccountIdentity> {
let data = self.owned_account()?.lock()?;
let state = data.state.as_ref().ok_or_else(transferred)?;
Ok(AccountIdentity {
uin: state.uin,
own_username: state.own_username.clone(),
})
}
pub fn account_lease(&self) -> Result<AccountLease> {
let account = self.owned_account()?;
let data = account.lock()?;
if !account.authority.active.load(Ordering::Acquire) {
return Err(data.interruption().because("Account is stopped"));
}
data.ensure_active("Account is stopped")?;
Ok(AccountLease {
authority: account.authority.clone(),
credential_generation: data.credential_generation,
})
}
pub fn export_account_state(&self) -> Result<AccountState> {
self.owned_account()?
.lock()?
.state
.as_ref()
.cloned()
.ok_or_else(transferred)
}
pub async fn shutdown(&self) -> Result<()> {
self.owned_account()?.stop_and_drain().await
}
pub fn stop(&self) -> Result<()> {
self.owned_account()?.stop()
}
pub fn prepare_logout(&self) -> Result<PendingLogout> {
let account = self.owned_account()?;
let (exchange, state) = account
.begin_with_terminal(true)
.map_err(|error| error.context(NativeRequestNotSubmitted))?;
Ok(PendingLogout {
exchange: Arc::new(exchange),
state,
options: self.options.clone(),
})
}
pub async fn stopped(&self) -> Result<()> {
self.owned_account()?.stopped().await;
Ok(())
}
pub async fn quiesce_and_export(&self) -> Result<AccountState> {
let account = self.owned_account()?;
account.stop_and_drain().await?;
let mut data = account.lock()?;
let state = data
.state
.take()
.context("Account state already transferred")?;
data.lifecycle = AccountLifecycle::Transferred;
Ok(state)
}
async fn account_request<T, F>(&self, operation: F) -> Result<T>
where
T: Send + 'static,
F: FnOnce(&NativeClient, &mut AccountState, &dyn Fn() -> Result<()>) -> Result<T>
+ Send
+ 'static,
{
let owner = self.owned_account()?;
let (exchange, state) = owner
.begin()
.map_err(|error| error.context(NativeRequestNotSubmitted))?;
let short_link = owner.short_link.clone();
let options = self.options.clone();
let cancellation = Arc::new(AtomicBool::new(false));
let _cancel_on_drop = CancelOnDrop(cancellation.clone());
tokio::task::spawn_blocking(move || {
Self::execute_account_request(
options,
exchange,
state,
short_link,
cancellation,
operation,
)
})
.await
.context("Account request worker failed")?
}
fn account_request_blocking<T, F>(&self, operation: F) -> Result<T>
where
F: FnOnce(&NativeClient, &mut AccountState, &dyn Fn() -> Result<()>) -> Result<T>,
{
let owner = self.owned_account()?;
let (exchange, state) = owner
.begin()
.map_err(|error| error.context(NativeRequestNotSubmitted))?;
Self::execute_account_request(
self.options.clone(),
exchange,
state,
owner.short_link.clone(),
Arc::new(AtomicBool::new(false)),
operation,
)
}
fn execute_account_request<T, F>(
options: NativeOptions,
exchange: Exchange,
mut state: AccountState,
short_link: Arc<crate::mmtls::ShortLinkCache>,
cancellation: Arc<AtomicBool>,
operation: F,
) -> Result<T>
where
F: FnOnce(&NativeClient, &mut AccountState, &dyn Fn() -> Result<()>) -> Result<T>,
{
let exchange = Arc::new(exchange);
let mut transport = NativeClient::new(options)?;
transport.short_link = Some(short_link);
let submission_exchange = exchange.clone();
let prior_admission = AtomicBool::new(false);
transport.submission_guard = Some(Arc::new(move || {
let check = (|| {
ensure!(
!cancellation.load(Ordering::Acquire),
"Account request cancelled before submission"
);
submission_exchange.check()
})();
match check {
Ok(()) => {
prior_admission.store(true, Ordering::Release);
Ok(())
}
Err(error) if !prior_admission.load(Ordering::Acquire) => {
Err(error.context(NativeRequestNotSubmitted))
}
Err(error) => Err(error),
}
}));
let result = operation(&transport, &mut state, &|| transport.check_submission());
let accepted = exchange.accept_cookie(&state);
match result {
Ok(value) => {
accepted?;
Ok(value)
}
Err(error) => match accepted {
Ok(()) => Err(error),
Err(account_error) => Err(error.context(account_error)),
},
}
}
}
#[path = "account_request.rs"]
mod request;
pub use request::AccountRequest;
#[path = "account_push.rs"]
mod push;
pub use push::AccountPushConnection;
#[path = "account_operations.rs"]
mod operations;
async fn wait_for_poll<R, C, S>(reply: R, cancellation: C, stopped: S) -> Result<Vec<u8>>
where
R: Future<Output = Result<Vec<u8>>>,
C: Future<Output = ()>,
S: Future<Output = ()>,
{
tokio::select! {
biased;
() = stopped => Err(crate::calls::host_transport::CallLiveSyncInterrupted.into()),
() = cancellation => Err(crate::calls::host_transport::CallLiveSyncInterrupted.into()),
result = reply => result,
}
}
#[cfg(test)]
#[path = "account_tests.rs"]
mod tests;