1#[cfg(test)]
18mod tests;
19mod writer;
20
21use std::future::Future;
22use std::pin::Pin;
23use std::sync::{Arc, Mutex, PoisonError};
24use std::time::Duration;
25
26use chrono::Utc;
27use tokio::sync::{mpsc, oneshot, watch};
28use tokio::task::JoinHandle;
29use tokio::time::{Instant, sleep_until};
30
31use crate::election::object_store::authority::writer::{Request, Resignation, Writer};
32use crate::election::object_store::{AuthorityHead, AuthorityState, HeadStore, NodeIdentity};
33use crate::error::{self, Error, Result};
34
35const LEASE: Duration = Duration::from_secs(10);
36const RENEW_INTERVAL: Duration = Duration::from_secs(5);
37const CLOCK_GUARD: Duration = Duration::from_secs(2);
38const GET_TIMEOUT: Duration = Duration::from_millis(500);
39const QUEUE_CAPACITY: usize = 32;
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub struct FencingToken {
44 epoch: u64,
45}
46
47impl FencingToken {
48 pub fn epoch(&self) -> u64 {
50 self.epoch
51 }
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum TakeoverOutcome {
57 Acquired(FencingToken),
59 AppliedButInactive,
61 NotEligible,
63}
64
65#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
67pub enum AuthorityStatus {
68 #[default]
70 Follower,
71 Leader { epoch: u64, deadline: Instant },
73 Resigning { epoch: u64, deadline: Instant },
75 RecoveryRequired,
77 Closed,
79}
80
81impl AuthorityStatus {
82 fn term(self) -> Option<(u64, Instant)> {
83 match self {
84 Self::Leader { epoch, deadline } | Self::Resigning { epoch, deadline } => {
85 Some((epoch, deadline))
86 }
87 _ => None,
88 }
89 }
90}
91
92#[derive(Debug, Default, Clone, Copy)]
94pub enum AuthorityPrecondition {
95 #[default]
97 Any,
98 WriteSeq(u64),
100}
101
102impl AuthorityPrecondition {
103 fn check(self, head: &AuthorityHead) -> Result<()> {
104 let actual = head.write_seq();
105 if let Self::WriteSeq(expected) = self
106 && actual != expected
107 {
108 return error::AuthorityWriteSeqMismatchSnafu { expected, actual }.fail();
109 }
110 Ok(())
111 }
112}
113
114#[derive(Debug, Clone, Copy)]
116pub enum AuthorityMutation {
117 Renew,
119 Resign,
121}
122
123pub struct Authority {
125 inner: Arc<Inner>,
126 request_tx: mpsc::Sender<Request>,
127 writer_task: tokio::sync::Mutex<Option<JoinHandle<()>>>,
128}
129
130impl Authority {
131 pub fn new(store: Arc<HeadStore>, identity: NodeIdentity) -> Self {
133 Self::start(
134 store,
135 identity,
136 || {
137 let now = Utc::now();
138 i128::from(now.timestamp()) * 1_000_000_000
139 + i128::from(now.timestamp_subsec_nanos())
140 },
141 QUEUE_CAPACITY,
142 common_runtime::spawn_global,
143 )
144 }
145
146 fn start(
147 store: Arc<HeadStore>,
148 identity: NodeIdentity,
149 wall_now_ns: impl Fn() -> i128 + Send + Sync + 'static,
150 capacity: usize,
151 spawn: impl FnOnce(Pin<Box<dyn Future<Output = ()> + Send>>) -> JoinHandle<()>,
152 ) -> Self {
153 let (status_tx, _) = watch::channel(AuthorityStatus::Follower);
154 let inner = Arc::new(Inner {
155 store,
156 identity,
157 wall_now_ns: Box::new(wall_now_ns),
158 control: Mutex::default(),
159 status_tx,
160 });
161 let (request_tx, request_rx) = mpsc::channel(capacity);
162 let writer_task = spawn(Box::pin(Writer::new(inner.clone(), request_rx).run()));
163 Self {
164 inner,
165 request_tx,
166 writer_task: tokio::sync::Mutex::new(Some(writer_task)),
167 }
168 }
169
170 pub async fn head(&self) -> Result<AuthorityState> {
172 self.inner.read(Admission::Read, None).await
173 }
174
175 pub fn status(&self) -> AuthorityStatus {
177 self.inner.update(|control, _| control.status)
178 }
179
180 pub async fn takeover(&self) -> Result<TakeoverOutcome> {
182 let (response, result) = oneshot::channel();
183 self.submit(Admission::Takeover, Request::Takeover(response))
184 .await?;
185 result.await.unwrap_or_else(|_| Err(closed()))
186 }
187
188 pub async fn mutate(
190 &self,
191 token: &FencingToken,
192 precondition: AuthorityPrecondition,
193 mutation: AuthorityMutation,
194 ) -> Result<()> {
195 let epoch = token.epoch;
196 let (response, result) = oneshot::channel();
197 match (mutation, precondition) {
198 (AuthorityMutation::Resign, AuthorityPrecondition::Any) => {
199 self.inner.update(|control, _| {
200 Admission::Renew(epoch).check(control.status)?;
201 let AuthorityStatus::Leader { deadline, .. } = control.status else {
202 return Err(rejected("term is inactive"));
203 };
204 control.status = AuthorityStatus::Resigning { epoch, deadline };
205 control.resignation = Some(Resignation { epoch, response });
206 Ok(())
207 })?;
208 }
209 (mutation, precondition) => {
210 let admission = match mutation {
211 AuthorityMutation::Renew => Admission::Renew(epoch),
212 AuthorityMutation::Resign => Admission::ConditionalResign(epoch),
213 };
214 self.submit(
215 admission,
216 Request::Mutate {
217 epoch,
218 mutation,
219 precondition,
220 response,
221 },
222 )
223 .await?;
224 }
225 }
226 result.await.unwrap_or_else(|_| Err(closed()))
227 }
228
229 pub async fn resign(&self, token: &FencingToken) -> Result<()> {
231 self.mutate(token, AuthorityPrecondition::Any, AuthorityMutation::Resign)
232 .await
233 }
234
235 pub async fn shutdown(&self) {
237 self.inner.close();
238 let mut writer_task = self.writer_task.lock().await;
239 if let Some(task) = writer_task.as_mut()
240 && let Err(error) = task.await
241 {
242 common_telemetry::warn!("Authority writer exited with error: {error}");
243 }
244 writer_task.take();
245 }
246
247 async fn submit(&self, admission: Admission, request: Request) -> Result<()> {
248 admission.check(self.status())?;
249 tokio::select! {
250 permit = self.request_tx.reserve() => {
251 let permit = permit.map_err(|_| closed())?;
252 self.inner.update(|control, _| {
253 admission.check(control.status)?;
254 permit.send(request);
255 Ok(())
256 })
257 }
258 _ = self.inner.wait_until(|status| admission.check(status).is_err()) => {
259 admission.check(self.status()).and_then(|()| Err(rejected("admission changed")))
260 }
261 }
262 }
263}
264
265impl Drop for Authority {
266 fn drop(&mut self) {
267 self.inner.close();
268 }
269}
270
271#[derive(Clone, Copy)]
272enum Admission {
273 Read,
274 Takeover,
275 Renew(u64),
276 ConditionalResign(u64),
277 Resign(u64),
278}
279
280impl Admission {
281 fn check(self, status: AuthorityStatus) -> Result<()> {
282 match (self, status) {
283 (_, AuthorityStatus::Closed) => Err(closed()),
284 (_, AuthorityStatus::RecoveryRequired) => error::AuthorityRecoveryRequiredSnafu.fail(),
285 (Self::Read, _) | (Self::Takeover, AuthorityStatus::Follower) => Ok(()),
286 (
287 Self::Renew(expected) | Self::ConditionalResign(expected),
288 AuthorityStatus::Leader { epoch, .. },
289 )
290 | (Self::Resign(expected), AuthorityStatus::Resigning { epoch, .. })
291 if expected == epoch =>
292 {
293 Ok(())
294 }
295 _ => Err(rejected(
296 "local state or fencing token does not authorize the operation",
297 )),
298 }
299 }
300}
301
302#[derive(Default)]
303struct Control {
304 status: AuthorityStatus,
305 resignation: Option<Resignation>,
306 snapshot: Option<SnapshotFloor>,
307}
308
309impl Control {
310 fn expire(&mut self, now: Instant) {
311 if self
312 .status
313 .term()
314 .is_some_and(|(_, deadline)| now >= deadline)
315 {
316 self.status = AuthorityStatus::Follower;
317 }
318 }
319
320 fn retire(&mut self, epoch: u64) {
321 if self
322 .status
323 .term()
324 .is_some_and(|(current, _)| current == epoch)
325 {
326 self.status = AuthorityStatus::Follower;
327 }
328 }
329}
330
331enum SnapshotFloor {
334 Observed(AuthorityState),
335 Applied {
336 head: AuthorityHead,
337 base: AuthorityState,
338 },
339}
340
341impl SnapshotFloor {
342 fn head(&self) -> &AuthorityHead {
343 match self {
344 Self::Observed(state) => state.head(),
345 Self::Applied { head, .. } => head,
346 }
347 }
348
349 fn validate(&self, store: &HeadStore, state: &AuthorityState) -> Result<()> {
350 let head = state.head();
351 let floor = self.head();
352 if head.epoch() < floor.epoch()
353 || head.write_seq() < floor.write_seq()
354 || (head.write_seq() == floor.write_seq() && head != floor)
355 {
356 return Err(invalid_snapshot(
357 "Head moved behind an observed or applied write",
358 ));
359 }
360 let (metadata, expect_same_version) = match self {
361 Self::Observed(previous) => {
362 (previous.metadata(), head.write_seq() == floor.write_seq())
363 }
364 Self::Applied { base, .. } => (base.metadata(), false),
365 };
366 if store.same_version(metadata, state.metadata())? != expect_same_version {
367 return Err(invalid_snapshot(
368 "conditional version disagrees with Head write sequence",
369 ));
370 }
371 Ok(())
372 }
373}
374
375struct Inner {
376 store: Arc<HeadStore>,
377 identity: NodeIdentity,
378 wall_now_ns: Box<dyn Fn() -> i128 + Send + Sync>,
379 control: Mutex<Control>,
380 status_tx: watch::Sender<AuthorityStatus>,
381}
382
383impl Inner {
384 fn update<T>(&self, f: impl FnOnce(&mut Control, Instant) -> T) -> T {
386 let mut control = self.control.lock().unwrap_or_else(PoisonError::into_inner);
387 let before = control.status;
388 let now = Instant::now();
389 control.expire(now);
390 let result = f(&mut control, now);
391 if control.status != before {
392 self.status_tx.send_replace(control.status);
393 }
394 result
395 }
396
397 async fn wait_until(&self, predicate: impl Fn(AuthorityStatus) -> bool) {
398 let mut status = self.status_tx.subscribe();
399 let _ = status.wait_for(|status| predicate(*status)).await;
400 }
401
402 fn close(&self) {
403 self.update(|control, _| control.status = AuthorityStatus::Closed);
404 }
405
406 async fn read(
407 &self,
408 admission: Admission,
409 deadline: Option<Instant>,
410 ) -> Result<AuthorityState> {
411 self.update(|control, _| admission.check(control.status))?;
412 let now = Instant::now();
413 let stop = deadline.map_or(now + GET_TIMEOUT, |end| end.min(now + GET_TIMEOUT));
414 if now >= stop {
415 return Err(timeout("read"));
416 }
417 let result = tokio::select! {
418 biased;
419 _ = self.wait_until(|status| admission.check(status).is_err()) => {
420 return self.update(|control, _| {
421 admission.check(control.status)?;
422 Err(rejected("read admission changed"))
423 });
424 }
425 result = self.store.read_head() => result,
426 _ = sleep_until(stop) => return Err(timeout("read")),
427 };
428 if matches!(result, Err(Error::AuthorityMissing { .. })) {
429 self.update(|control, _| {
430 if control.status != AuthorityStatus::Closed {
431 control.status = AuthorityStatus::RecoveryRequired;
432 }
433 });
434 }
435 let state = result?;
436 if Instant::now() >= stop {
437 return Err(timeout("read"));
438 }
439 self.observe(admission, &state)?;
440 Ok(state)
441 }
442
443 fn observe(&self, admission: Admission, state: &AuthorityState) -> Result<()> {
444 self.update(|control, _| {
445 let head = state.head();
446 if let Some(floor) = &control.snapshot {
447 if matches!(admission, Admission::Read)
451 && head.write_seq() < floor.head().write_seq()
452 && head.epoch() <= floor.head().epoch()
453 {
454 return Ok(());
455 }
456 floor.validate(&self.store, state)?;
457 }
458 if let Some((epoch, _)) = control.status.term()
459 && head.epoch() >= epoch
460 && (head.epoch() != epoch || head.owner.as_ref() != Some(&self.identity))
461 {
462 control.retire(epoch);
463 }
464 control.snapshot = Some(SnapshotFloor::Observed(state.clone()));
465 Ok(())
466 })
467 }
468
469 fn diagnostic_deadline(&self) -> u64 {
470 let ns = (self.wall_now_ns)().saturating_add(LEASE.as_nanos() as i128);
471 u64::try_from(ns / 1_000_000).unwrap_or(if ns < 0 { 0 } else { u64::MAX })
472 }
473}
474
475fn closed() -> Error {
476 error::AuthorityClosedSnafu.build()
477}
478
479fn rejected(reason: &'static str) -> Error {
480 error::AuthorityRejectedSnafu { reason }.build()
481}
482
483fn invalid_snapshot(reason: &'static str) -> Error {
484 error::AuthorityMetadataSnafu { reason }.build()
485}
486
487fn timeout(operation: &'static str) -> Error {
488 error::AuthorityTimeoutSnafu { operation }.build()
489}