use alloc::string::ToString;
use alloc::vec::Vec;
use crate::connect::proto::{
AccessToken, Backoff, CommunicationDetails, NodeId, SessionCredentials, SessionGrant,
SessionInitClient, TokenStore,
};
use crate::connect::tls::TlsPolicy;
use crate::types::{ProtocolVersion, Timestamp};
use super::http::{Error, Http};
const INITIATE_SESSION: &str = "initiateSession";
const CONFIRM_ACCESS_TOKEN: &str = "confirmAccessToken";
const UNPAIR: &str = "unpair";
#[derive(Debug)]
pub struct Session {
http: Http,
machine: SessionInitClient,
client_node_id: NodeId,
server_node_id: NodeId,
backoff: Backoff,
attempt: u32,
}
impl Session {
pub const REQUEST_TIMEOUT: core::time::Duration = core::time::Duration::from_secs(10);
pub fn new(
base_url: &str,
policy: &TlsPolicy,
client_node_id: NodeId,
server_node_id: NodeId,
tokens: TokenStore,
) -> Result<Self, Error> {
if !policy.authenticates() {
return Err(Error::Url(
"a session must not run under the pairing-only TLS policy".to_string(),
));
}
Ok(Self {
http: Http::new(base_url, policy, Self::REQUEST_TIMEOUT)?,
machine: SessionInitClient::new(client_node_id, server_node_id, tokens),
client_node_id,
server_node_id,
backoff: Backoff::default(),
attempt: 0,
})
}
#[must_use]
pub fn with_s2_message_versions(mut self, versions: Vec<ProtocolVersion>) -> Self {
let tokens = self.machine.tokens().clone();
self.machine = SessionInitClient::new(self.client_node_id, self.server_node_id, tokens)
.with_s2_message_versions(versions);
self
}
#[must_use]
pub fn tokens(&self) -> &TokenStore {
self.machine.tokens()
}
pub async fn initiate(&mut self, now: Timestamp) -> Result<SessionCredentials, Error> {
let result = self.attempt(now).await;
if let Err(e) = &result
&& !matches!(
e,
Error::Protocol(crate::connect::proto::ConnectError::SessionRefused(refused))
if refused.error_message == crate::connect::proto::SessionErrorMessage::NoLongerPaired
)
{
self.machine.restart();
}
result
}
async fn attempt(&mut self, now: Timestamp) -> Result<SessionCredentials, Error> {
loop {
let (bearer, body) = self.machine.initiate()?;
let grant: SessionGrant = match self
.http
.post(
"initiateSession",
INITIATE_SESSION,
Some(bearer.as_str()),
&body,
)
.await
{
Ok(grant) => grant,
Err(Error::Http { status, .. }) if status.is_unauthorized() => {
crate::trace::event!(
warn,
remaining = self.machine.tokens().len(),
"the access token was refused; trying the next"
);
self.machine.unauthorized()?;
continue;
}
Err(Error::Http {
status,
detail: Some(detail),
..
}) if status.0 == 400 => {
if let Ok(refused) =
serde_json::from_str::<crate::connect::proto::SessionRefused>(&detail)
{
if refused.error_message
== crate::connect::proto::SessionErrorMessage::NoLongerPaired
{
let _ = self.machine.unpaired();
}
return Err(Error::Protocol(
crate::connect::proto::ConnectError::SessionRefused(refused),
));
}
return Err(Error::Http {
operation: "initiateSession",
status,
detail: Some(detail),
});
}
Err(e) => return Err(e),
};
self.machine.accept(grant, now)?;
let confirm = self.machine.confirm()?;
let details: CommunicationDetails = self
.http
.post_bodyless(
"confirmAccessToken",
CONFIRM_ACCESS_TOKEN,
Some(confirm.as_str()),
)
.await?;
let credentials = self.machine.connected(details, now)?;
crate::trace::event!(
info,
url = %credentials.websocket_url,
profile = ?credentials.profile,
expires = %credentials.expires(),
"session initiated"
);
self.attempt = 0;
return Ok(credentials);
}
}
pub async fn unpair(&mut self) -> Result<(), Error> {
let token = self.machine.tokens().current().cloned();
let body = self.machine.unpaired();
let Some(token) = token else {
return Ok(());
};
self.http
.post_empty("unpair", UNPAIR, Some(token.as_str()), Some(&body))
.await
}
pub fn backoff(&mut self) -> core::time::Duration {
let delay = self.backoff.delay_with(self.attempt);
self.attempt = self.attempt.saturating_add(1);
core::time::Duration::from(delay)
}
pub fn reset_backoff(&mut self) {
self.attempt = 0;
}
#[must_use]
pub fn access_token(&self) -> Option<&AccessToken> {
self.machine.tokens().current()
}
}