1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
//! 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", &"<redacted>")
.field("refresh_jwt", &"<redacted>")
.finish()
}
}
#[derive(Default)]
struct State {
session: Option<Session>,
generation: u64,
}
pub struct SessionManager {
api: Arc<dyn PdsApi>,
handle: String,
password: String,
governor: Arc<RateGovernor>,
logger: Logger,
time: Arc<dyn Time>,
/// Serializes createSession/refreshSession so a burst of 401s produces one
/// login or one refresh, not one per worker.
login_lock: Mutex<()>,
state: RwLock<State>,
repo: std::sync::OnceLock<String>,
login_calls: AtomicU64,
}
impl SessionManager {
pub fn new(
api: Arc<dyn PdsApi>,
handle: String,
password: String,
governor: Arc<RateGovernor>,
logger: Logger,
time: Arc<dyn Time>,
) -> 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<Session> {
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<Session> {
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<Session> {
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<Session> {
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<String>) -> PdsError {
PdsError::new(PdsErrorKind::Other, message)
}