use std::future::Future;
use std::pin::pin;
use std::sync::Arc;
use tokio::time::Instant;
use super::attempt::{AttemptBudget, Attempted, InteractiveFetchError};
use super::key::{LookupKey, LookupKind};
use super::memo::Decision;
use super::{
InteractiveFetch, InteractiveFetchGate, InteractiveFetchRequest, NoLiveList, SharedVersions,
log_skipped, now,
};
use crate::freshness::FreshnessSettings;
use crate::single_flight::{Claim, Follower, claim_or_follow};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(super) enum ListShape {
Bare,
Enriched,
}
impl ListShape {
pub(super) const fn of(freshness: FreshnessSettings) -> Self {
match freshness {
FreshnessSettings::Disabled => Self::Bare,
FreshnessSettings::Enabled { .. } => Self::Enriched,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(super) struct FlightKey {
key: Arc<LookupKey>,
shape: ListShape,
generation: u64,
}
impl FlightKey {
pub(super) const fn new(key: Arc<LookupKey>, shape: ListShape, generation: u64) -> Self {
Self {
key,
shape,
generation,
}
}
fn with_shape(&self, shape: ListShape) -> Self {
Self {
key: Arc::clone(&self.key),
shape,
generation: self.generation,
}
}
}
#[derive(Clone)]
pub(super) enum FlightResult {
Live(SharedVersions),
Failed,
}
impl std::fmt::Debug for FlightResult {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Live(list) => f.debug_tuple("Live").field(&list.len()).finish(),
Self::Failed => f.write_str("Failed"),
}
}
}
impl FlightResult {
fn of(result: &InteractiveFetch<SharedVersions>) -> Self {
match result {
InteractiveFetch::Live(list) => Self::Live(Arc::clone(list)),
InteractiveFetch::Degraded(_) => Self::Failed,
}
}
fn into_fetch(self) -> InteractiveFetch<SharedVersions> {
match self {
Self::Live(list) => InteractiveFetch::Live(list),
Self::Failed => InteractiveFetch::Degraded(NoLiveList::Unverified),
}
}
}
enum Followed {
Result(FlightResult),
LeaderGone,
DeadlineElapsed,
}
impl InteractiveFetchGate {
#[cfg(test)]
pub(super) fn in_flight_len(&self) -> usize {
self.version_flights.len()
}
fn claim_or_follow(&self, flight: &FlightKey) -> Claim<'_, FlightKey, FlightResult> {
if flight.shape == ListShape::Bare
&& let Some(enriched) = self
.version_flights
.get(&flight.with_shape(ListShape::Enriched))
.map(|entry| entry.clone())
{
return Claim::Follower(Follower::from(enriched));
}
claim_or_follow(&self.version_flights, flight.clone())
}
}
async fn follow(follower: Follower<FlightResult>, deadline: Instant) -> Followed {
match tokio::time::timeout_at(deadline, follower.wait()).await {
Ok(Some(result)) => Followed::Result(result),
Ok(None) => Followed::LeaderGone,
Err(_) => Followed::DeadlineElapsed,
}
}
pub(super) async fn await_shared<E: InteractiveFetchError>(
gate: &InteractiveFetchGate,
lookup: Arc<LookupKey>,
fetch: impl Future<Output = Result<SharedVersions, E>>,
request: &InteractiveFetchRequest<'_>,
shape: ListShape,
) -> InteractiveFetch<SharedVersions> {
let admitted = match gate.admit_request(&lookup, request) {
Ok(admitted) => admitted,
Err(kind) => return InteractiveFetch::Degraded(kind),
};
let (generation, background_failure_known) =
(admitted.generation, admitted.background_failure_known);
let deadline = Instant::now() + LookupKind::VersionList.budget();
let flight = FlightKey::new(Arc::clone(&lookup), shape, generation);
let mut fetch = pin!(fetch);
loop {
match gate.claim_or_follow(&flight) {
Claim::Follower(follower) => match follow(follower, deadline).await {
Followed::Result(result) => return result.into_fetch(),
Followed::LeaderGone => {}
Followed::DeadlineElapsed => {
log_skipped(request, "deadline elapsed following another request");
return InteractiveFetch::Degraded(NoLiveList::Unverified);
}
},
Claim::Leader(leader) => {
match lead(
gate,
fetch.as_mut(),
deadline,
&lookup,
request,
background_failure_known,
generation,
)
.await
{
Led::Answered(result) => {
leader.publish(FlightResult::of(&result));
return result;
}
Led::Unanswered(result) => return result,
}
}
}
}
}
enum Led {
Answered(InteractiveFetch<SharedVersions>),
Unanswered(InteractiveFetch<SharedVersions>),
}
async fn lead<E: InteractiveFetchError>(
gate: &InteractiveFetchGate,
fetch: impl Future<Output = Result<SharedVersions, E>>,
deadline: Instant,
lookup: &Arc<LookupKey>,
request: &InteractiveFetchRequest<'_>,
background_failure_known: bool,
generation: u64,
) -> Led {
if let Decision::Degrade(kind, reason) =
gate.decide(lookup, background_failure_known, generation, now())
{
log_skipped(request, reason.as_str());
return Led::Answered(InteractiveFetch::Degraded(kind));
}
if Instant::now() >= deadline {
log_skipped(request, "deadline elapsed before the lookup could start");
return Led::Unanswered(InteractiveFetch::Degraded(NoLiveList::Unverified));
}
match gate
.attempt(
fetch,
deadline,
lookup,
request,
background_failure_known,
generation,
)
.await
{
Attempted::Polled(result @ InteractiveFetch::Degraded(_), AttemptBudget::Truncated) => {
Led::Unanswered(result)
}
Attempted::Polled(result, AttemptBudget::Full | AttemptBudget::Truncated) => {
Led::Answered(result)
}
Attempted::Refused => Led::Unanswered(InteractiveFetch::Degraded(NoLiveList::Unverified)),
}
}