//! PDS session state and single-flight login/refresh. //! //! Every worker shares one `SessionManager`. A `401` from any worker calls //! [`SessionManager::reauth`]; the first caller refreshes (or re-logs in) while //! the rest wait on the same mutex and then reuse the new credential. The //! generation counter lets a waiter tell "somebody already replaced the token //! I used" from "the token I used is still current", even when the PDS hands //! back the same access JWT. use std::fmt; use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Duration; use serde_json::Value; use tokio::sync::{Mutex, RwLock}; use crate::constants::CREATE_SESSION_ATTEMPTS; use crate::log::Logger; use crate::time::Time; use super::error::{PdsError, PdsErrorKind, classify_at, log_rate_limited}; use super::governor::RateGovernor; use super::{PdsApi, XrpcResponse}; #[derive(Clone)] pub struct Session { pub did: String, pub handle: String, pub access_jwt: String, pub refresh_jwt: String, } impl Session { pub fn did(&self) -> &str { &self.did } } impl fmt::Debug for Session { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter .debug_struct("Session") .field("did", &self.did) .field("handle", &self.handle) .field("access_jwt", &"") .field("refresh_jwt", &"") .finish() } } #[derive(Default)] struct State { session: Option, generation: u64, } pub struct SessionManager { api: Arc, handle: String, password: String, governor: Arc, logger: Logger, time: Arc, /// Serializes createSession/refreshSession so a burst of 401s produces one /// login or one refresh, not one per worker. login_lock: Mutex<()>, state: RwLock, repo: std::sync::OnceLock, login_calls: AtomicU64, } impl SessionManager { pub fn new( api: Arc, handle: String, password: String, governor: Arc, logger: Logger, time: Arc, ) -> Self { Self { api, handle, password, governor, logger, time, login_lock: Mutex::new(()), state: RwLock::new(State::default()), repo: std::sync::OnceLock::new(), login_calls: AtomicU64::new(0), } } /// The repository identifier: the handle until a session names its DID. pub fn repo(&self) -> &str { match self.repo.get() { Some(did) => did.as_str(), None => self.handle.as_str(), } } pub fn login_calls(&self) -> u64 { self.login_calls.load(Ordering::Relaxed) } pub async fn generation(&self) -> u64 { self.state.read().await.generation } /// The current credential and the generation it was stored at. pub async fn snapshot(&self) -> Option<(Session, u64)> { let state = self.state.read().await; state .session .clone() .map(|session| (session, state.generation)) } /// createSession, retrying `429` up to [`CREATE_SESSION_ATTEMPTS`] times. pub async fn login(&self) -> anyhow::Result { let _guard = self.login_lock.lock().await; self.login_locked().await } /// Recover from a `401` on a call that used `stale_access`. /// /// If another worker already replaced that credential (newer generation, or /// a different access JWT), reuse it. Otherwise try refreshSession; if that /// fails or expires, fall back to a fresh createSession. pub async fn reauth( &self, stale_access: &str, seen_generation: u64, ) -> anyhow::Result { let _guard = self.login_lock.lock().await; let current = { let state = self.state.read().await; state .session .clone() .map(|session| (session, state.generation)) }; if let Some((session, generation)) = ¤t && (session.access_jwt != stale_access || *generation > seen_generation) { return Ok(session.clone()); } if let Some((session, _)) = ¤t && !session.refresh_jwt.is_empty() { match self.api.refresh_session(&session.refresh_jwt).await { Ok(response) if is_success(response.status) => { if let Ok(refreshed) = parse_session(&response, Some(session)) { self.store(refreshed.clone()).await; return Ok(refreshed); } } _ => {} } } self.login_locked().await } /// Caller holds `login_lock`. async fn login_locked(&self) -> anyhow::Result { let mut attempt = 1; loop { self.governor.request().await?; let response = self .api .create_session(&self.handle, &self.password) .await?; if is_success(response.status) { let session = parse_session(&response, None)?; self.store(session.clone()).await; self.login_calls.fetch_add(1, Ordering::Relaxed); self.governor.bind(&session.did).await?; let _ = self.repo.set(session.did.clone()); return Ok(session); } let error = classify_at( Some(response.status), &response.headers, &response.text(), None, self.time.now_unix(), ); if error.kind != PdsErrorKind::RateLimited || attempt >= CREATE_SESSION_ATTEMPTS { return Err(error.into()); } let delay = error.retry_after.unwrap_or(0.0).max(300.0); log_rate_limited( &self.logger, &error, &response.headers, "createSession", None, None, delay, attempt, ); self.governor.record_wait(delay); self.time.sleep(Duration::from_secs_f64(delay)).await; attempt += 1; } } async fn store(&self, session: Session) { let mut state = self.state.write().await; state.session = Some(session); state.generation += 1; } } pub fn is_success(status: u16) -> bool { (200..300).contains(&status) } /// Build a session from a createSession/refreshSession body, keeping the old /// handle/refresh token when the PDS omits them (refresh responses rotate /// selectively). fn parse_session(response: &XrpcResponse, previous: Option<&Session>) -> anyhow::Result { let body = &response.body; let field = |name: &str| body.get(name).and_then(Value::as_str); let did = field("did") .or_else(|| previous.map(|session| session.did.as_str())) .ok_or_else(|| anyhow::anyhow!("session response missing did"))? .to_owned(); let access_jwt = field("accessJwt") .ok_or_else(|| anyhow::anyhow!("session response missing accessJwt"))? .to_owned(); let refresh_jwt = field("refreshJwt") .or_else(|| previous.map(|session| session.refresh_jwt.as_str())) .unwrap_or_default() .to_owned(); let handle = field("handle") .or_else(|| previous.map(|session| session.handle.as_str())) .unwrap_or_default() .to_owned(); Ok(Session { did, handle, access_jwt, refresh_jwt, }) } /// Convert a non-session error into the classifier shape so the retry loop can /// keep one error type. pub fn error_from_message(message: impl Into) -> PdsError { PdsError::new(PdsErrorKind::Other, message) }