use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use super::candidate::ProjectArtifacts;
use super::candidate::SourceId;
use super::supervisor::SourceSupervisor;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SelectionRefusal {
EmptySelection,
MissingSource(SourceId),
DuplicateSource(SourceId),
MismatchedGeneration {
source: SourceId,
expected: u64,
found: u64,
},
NotCurrent(SourceId),
StaleAtFinalization(SourceId),
RetargetedDuringLease,
ForeignTable,
ProtectedRootRequiresPromotion(SourceId),
}
impl SelectionRefusal {
pub fn transport_code(&self) -> &'static str {
match self {
SelectionRefusal::EmptySelection => "selection_empty",
SelectionRefusal::MissingSource(_) => "selection_missing_source",
SelectionRefusal::DuplicateSource(_) => "selection_duplicate_source",
SelectionRefusal::MismatchedGeneration { .. } => "selection_generation_mismatch",
SelectionRefusal::NotCurrent(_) => "source_not_current",
SelectionRefusal::StaleAtFinalization(_) => "lease_stale_at_finalization",
SelectionRefusal::RetargetedDuringLease => "lease_retargeted",
SelectionRefusal::ForeignTable => "lease_foreign_table",
SelectionRefusal::ProtectedRootRequiresPromotion(_) => {
"protected_root_requires_promotion"
}
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OutputCoverage {
Full,
Truncated,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RenderIdentity {
pub source_truth: BTreeMap<SourceId, u64>,
pub cache_identity: u64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Rendering {
pub coverage: OutputCoverage,
pub identity: RenderIdentity,
pub body_len: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum QueryOutcome {
Matches(usize),
NoMatch,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HealthSurface {
Health,
HealthCompact,
Status,
HealthResource,
}
impl HealthSurface {
pub const ALL: [HealthSurface; 4] = [
HealthSurface::Health,
HealthSurface::HealthCompact,
HealthSurface::Status,
HealthSurface::HealthResource,
];
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct HealthProjection {
pub committed_generations: u64,
pub bounded_attempts: u64,
}
#[derive(Clone, Debug, Default)]
pub struct SelectedAggregate {
pub sources: Vec<(SourceId, u64)>,
}
impl SelectedAggregate {
pub fn of(sources: impl IntoIterator<Item = (u64, u64)>) -> Self {
Self {
sources: sources
.into_iter()
.map(|(id, generation)| (SourceId(id), generation))
.collect(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SourceState {
Current { generation: u64 },
NonCurrent { last_generation: u64 },
}
static NEXT_RANKING_SNAPSHOT: AtomicU64 = AtomicU64::new(1);
static NEXT_TABLE_IDENTITY: AtomicU64 = AtomicU64::new(1);
#[derive(Debug)]
pub struct ProjectQueryTable {
identity: u64,
sources: BTreeMap<SourceId, SourceState>,
protected: BTreeSet<SourceId>,
target_epoch: u64,
}
impl Default for ProjectQueryTable {
fn default() -> Self {
Self {
identity: NEXT_TABLE_IDENTITY.fetch_add(1, Ordering::Relaxed),
sources: BTreeMap::new(),
protected: BTreeSet::new(),
target_epoch: 0,
}
}
}
#[derive(Debug)]
pub struct StrictSelectionLease {
table_identity: u64,
captured: BTreeMap<SourceId, u64>,
ranking_snapshot: u64,
target_epoch: u64,
}
#[derive(Debug)]
pub struct CompletedLease {
captured: BTreeMap<SourceId, u64>,
}
impl ProjectQueryTable {
pub fn new() -> Self {
Self::default()
}
pub fn publish_current(&mut self, source: SourceId, generation: u64) {
assert!(
!self.protected.contains(&source),
"protected roots publish only through full candidate promotion"
);
self.sources
.insert(source, SourceState::Current { generation });
}
pub fn mark_non_current(&mut self, source: SourceId) {
let last_generation = match self.sources.get(&source) {
Some(SourceState::Current { generation }) => *generation,
Some(SourceState::NonCurrent { last_generation }) => *last_generation,
None => 0,
};
self.sources
.insert(source, SourceState::NonCurrent { last_generation });
}
pub fn declare_protected(&mut self, source: SourceId) {
self.protected.insert(source);
if let Some(SourceState::Current { generation }) = self.sources.get(&source) {
let last_generation = *generation;
self.sources
.insert(source, SourceState::NonCurrent { last_generation });
}
}
pub fn publish_without_promotion(
&mut self,
source: SourceId,
generation: u64,
) -> Result<(), SelectionRefusal> {
if self.protected.contains(&source) {
return Err(SelectionRefusal::ProtectedRootRequiresPromotion(source));
}
self.sources
.insert(source, SourceState::Current { generation });
Ok(())
}
pub fn publish_protected_from_promotion(
&mut self,
source: SourceId,
promotion: &ProjectArtifacts,
probe: impl FnMut(),
) -> Result<(), SelectionRefusal> {
let _ = promotion;
let _ = probe;
let next = match self.sources.get(&source) {
Some(SourceState::Current { generation }) => generation + 1,
Some(SourceState::NonCurrent { last_generation }) => last_generation + 1,
None => 1,
};
self.sources
.insert(source, SourceState::Current { generation: next });
Ok(())
}
pub fn retarget(&mut self) {
self.target_epoch += 1;
}
pub fn acquire_strict(
&self,
selection: &SelectedAggregate,
) -> Result<StrictSelectionLease, SelectionRefusal> {
if selection.sources.is_empty() {
return Err(SelectionRefusal::EmptySelection);
}
let mut captured = BTreeMap::new();
for (source, expected) in &selection.sources {
if captured.contains_key(source) {
return Err(SelectionRefusal::DuplicateSource(*source));
}
match self.sources.get(source) {
None => return Err(SelectionRefusal::MissingSource(*source)),
Some(SourceState::NonCurrent { .. }) => {
return Err(SelectionRefusal::NotCurrent(*source));
}
Some(SourceState::Current { generation }) => {
if generation != expected {
return Err(SelectionRefusal::MismatchedGeneration {
source: *source,
expected: *expected,
found: *generation,
});
}
captured.insert(*source, *generation);
}
}
}
Ok(StrictSelectionLease {
table_identity: self.identity,
captured,
ranking_snapshot: NEXT_RANKING_SNAPSHOT.fetch_add(1, Ordering::Relaxed),
target_epoch: self.target_epoch,
})
}
pub fn health(
&self,
surface: HealthSurface,
supervisor: &SourceSupervisor,
) -> HealthProjection {
let _ = surface;
HealthProjection {
committed_generations: supervisor.committed_generations(),
bounded_attempts: supervisor.attempt_records().len() as u64,
}
}
}
pub fn acquire_multi_project(
selections: &[(&ProjectQueryTable, &SelectedAggregate)],
) -> Result<Vec<StrictSelectionLease>, SelectionRefusal> {
let mut leases = Vec::with_capacity(selections.len());
for (table, selection) in selections {
leases.push(table.acquire_strict(selection)?);
}
Ok(leases)
}
fn cache_identity_of(captured: &BTreeMap<SourceId, u64>) -> u64 {
captured
.iter()
.fold(0xcbf2_9ce4_8422_2325_u64, |acc, (source, generation)| {
acc.wrapping_mul(0x0100_0000_01b3)
.wrapping_add(source.0)
.wrapping_mul(0x0100_0000_01b3)
.wrapping_add(*generation)
})
}
impl StrictSelectionLease {
pub fn captured(&self) -> BTreeMap<SourceId, u64> {
self.captured.clone()
}
pub fn ranking_snapshot(&self) -> u64 {
self.ranking_snapshot
}
pub fn finalize(self, table: &ProjectQueryTable) -> Result<CompletedLease, SelectionRefusal> {
if table.identity != self.table_identity {
return Err(SelectionRefusal::ForeignTable);
}
if table.target_epoch != self.target_epoch {
return Err(SelectionRefusal::RetargetedDuringLease);
}
for (source, generation) in &self.captured {
match table.sources.get(source) {
Some(SourceState::Current { generation: live }) if live == generation => {}
_ => return Err(SelectionRefusal::StaleAtFinalization(*source)),
}
}
Ok(CompletedLease {
captured: self.captured,
})
}
}
impl CompletedLease {
pub fn query(&self, needle: u64) -> QueryOutcome {
let matches = self
.captured
.values()
.filter(|generation| **generation == needle)
.count();
if matches == 0 {
QueryOutcome::NoMatch
} else {
QueryOutcome::Matches(matches)
}
}
pub fn render(&self, max_len: usize) -> Rendering {
let full_body: String = self
.captured
.iter()
.map(|(source, generation)| format!("{}:{generation};", source.0))
.collect();
let coverage = if max_len >= full_body.len() {
OutputCoverage::Full
} else {
OutputCoverage::Truncated
};
Rendering {
coverage,
identity: RenderIdentity {
source_truth: self.captured.clone(),
cache_identity: cache_identity_of(&self.captured),
},
body_len: full_body.len().min(max_len),
}
}
}