use std::num::NonZeroU64;
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT_IDENTITY: AtomicU64 = AtomicU64::new(1);
fn next_identity() -> NonZeroU64 {
let raw = NEXT_IDENTITY.fetch_add(1, Ordering::Relaxed);
NonZeroU64::new(raw).expect("identity counter starts at 1 and only increases")
}
macro_rules! identity_newtype {
($(#[$meta:meta])* $name:ident) => {
$(#[$meta])*
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct $name(NonZeroU64);
impl $name {
pub fn fresh() -> Self {
Self(next_identity())
}
}
};
}
identity_newtype!(
BindingIdentity
);
identity_newtype!(
ObserverToken
);
identity_newtype!(
CandidateIdentity
);
identity_newtype!(
GenerationIdentity
);
identity_newtype!(
PublicationIdentity
);
identity_newtype!(
SnapshotIdentity
);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct MutationEpoch(u64);
impl MutationEpoch {
pub const fn initial() -> Self {
Self(0)
}
fn advanced(self) -> Self {
Self(self.0 + 1)
}
pub const fn get(self) -> u64 {
self.0
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BindingAuthority {
identity: BindingIdentity,
physical_root: crate::live_index::index_lifecycle::physical_root::PhysicalRootIdentity,
}
impl BindingAuthority {
pub fn bind(
physical_root: crate::live_index::index_lifecycle::physical_root::PhysicalRootIdentity,
) -> Self {
Self {
identity: BindingIdentity::fresh(),
physical_root,
}
}
pub fn identity(&self) -> BindingIdentity {
self.identity
}
pub fn physical_root(
&self,
) -> crate::live_index::index_lifecycle::physical_root::PhysicalRootIdentity {
self.physical_root
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CandidateAuthority {
identity: CandidateIdentity,
binding: BindingAuthority,
observer_cut: ObserverToken,
}
impl CandidateAuthority {
pub fn open(binding: BindingAuthority, observer_cut: ObserverToken) -> Self {
Self {
identity: CandidateIdentity::fresh(),
binding,
observer_cut,
}
}
pub fn identity(&self) -> CandidateIdentity {
self.identity
}
pub fn binding(&self) -> &BindingAuthority {
&self.binding
}
pub fn observer_cut(&self) -> ObserverToken {
self.observer_cut
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct MutationAuthority {
generation: GenerationIdentity,
binding: BindingAuthority,
epoch: MutationEpoch,
publication: PublicationIdentity,
}
impl MutationAuthority {
pub fn generation(&self) -> GenerationIdentity {
self.generation
}
pub fn binding(&self) -> &BindingAuthority {
&self.binding
}
pub fn epoch(&self) -> MutationEpoch {
self.epoch
}
pub fn publication(&self) -> PublicationIdentity {
self.publication
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct NonCurrentPublicationProof {
publication: PublicationIdentity,
epoch: MutationEpoch,
}
impl NonCurrentPublicationProof {
pub fn publication(&self) -> PublicationIdentity {
self.publication
}
pub fn epoch(&self) -> MutationEpoch {
self.epoch
}
}
#[derive(Debug)]
pub struct CurrentMutationGrantAuthority {
authority: MutationAuthority,
published_non_current: NonCurrentPublicationProof,
}
impl CurrentMutationGrantAuthority {
pub fn authority(&self) -> &MutationAuthority {
&self.authority
}
pub fn published_non_current(&self) -> &NonCurrentPublicationProof {
&self.published_non_current
}
pub(crate) fn into_parts(self) -> (MutationAuthority, NonCurrentPublicationProof) {
(self.authority, self.published_non_current)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurrentPublication {
publication: PublicationIdentity,
generation: GenerationIdentity,
binding: BindingAuthority,
observer_cut: ObserverToken,
}
impl CurrentPublication {
pub fn promote(binding: BindingAuthority, observer_cut: ObserverToken) -> Self {
Self {
publication: PublicationIdentity::fresh(),
generation: GenerationIdentity::fresh(),
binding,
observer_cut,
}
}
pub fn publication(&self) -> PublicationIdentity {
self.publication
}
pub fn generation(&self) -> GenerationIdentity {
self.generation
}
pub fn binding(&self) -> &BindingAuthority {
&self.binding
}
pub fn observer_cut(&self) -> ObserverToken {
self.observer_cut
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MutationGrantInput {
LiveCurrent(PublicationIdentity),
Candidate(CandidateIdentity),
Snapshot(SnapshotIdentity),
RetainedGeneration(GenerationIdentity),
StalePublication(PublicationIdentity),
}
impl MutationGrantInput {
fn provenance(&self) -> Provenance {
match self {
Self::LiveCurrent(_) => Provenance::LiveCurrent,
Self::Candidate(_) => Provenance::Candidate,
Self::Snapshot(_) => Provenance::Snapshot,
Self::RetainedGeneration(_) => Provenance::RetainedGeneration,
Self::StalePublication(_) => Provenance::StalePublication,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Provenance {
LiveCurrent,
Candidate,
Snapshot,
RetainedGeneration,
StalePublication,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PhaseName {
Loading,
Current,
Refreshing,
Blocked,
Stopping,
}
#[derive(Debug)]
enum SourcePhase {
Loading,
Current(CurrentPublication),
Refreshing {
retained: GenerationIdentity,
binding: BindingAuthority,
publication: PublicationIdentity,
},
Blocked {
retained: Option<GenerationIdentity>,
},
Stopping {
retained: Option<GenerationIdentity>,
},
}
impl SourcePhase {
fn name(&self) -> PhaseName {
match self {
Self::Loading => PhaseName::Loading,
Self::Current(_) => PhaseName::Current,
Self::Refreshing { .. } => PhaseName::Refreshing,
Self::Blocked { .. } => PhaseName::Blocked,
Self::Stopping { .. } => PhaseName::Stopping,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthorityRefusal {
PhaseNotCurrent {
phase: PhaseName,
},
ProvenanceNotLiveCurrent {
provenance: Provenance,
},
PublicationIdentityMismatch {
presented: PublicationIdentity,
live: PublicationIdentity,
},
PhysicalRootReplaced,
PermitAlreadyTerminal,
SideEffectAlreadyInFlight,
WholeAuthorityMismatch,
OutstandingPermit,
}
#[derive(Debug)]
pub struct SourceRuntime {
phase: SourcePhase,
mutation_epoch: MutationEpoch,
grants_issued: u64,
}
impl SourceRuntime {
pub fn loading() -> Self {
Self {
phase: SourcePhase::Loading,
mutation_epoch: MutationEpoch::initial(),
grants_issued: 0,
}
}
pub fn current(publication: CurrentPublication) -> Self {
Self {
phase: SourcePhase::Current(publication),
mutation_epoch: MutationEpoch::initial(),
grants_issued: 0,
}
}
pub fn refreshing(binding: BindingAuthority, retained: GenerationIdentity) -> Self {
Self {
phase: SourcePhase::Refreshing {
retained,
binding,
publication: PublicationIdentity::fresh(),
},
mutation_epoch: MutationEpoch::initial(),
grants_issued: 0,
}
}
pub fn blocked(retained: Option<GenerationIdentity>) -> Self {
Self {
phase: SourcePhase::Blocked { retained },
mutation_epoch: MutationEpoch::initial(),
grants_issued: 0,
}
}
pub fn stopping(retained: Option<GenerationIdentity>) -> Self {
Self {
phase: SourcePhase::Stopping { retained },
mutation_epoch: MutationEpoch::initial(),
grants_issued: 0,
}
}
pub fn phase(&self) -> PhaseName {
self.phase.name()
}
pub fn mutation_epoch(&self) -> MutationEpoch {
self.mutation_epoch
}
pub fn grants_issued(&self) -> u64 {
self.grants_issued
}
pub fn retained_generation(&self) -> Option<GenerationIdentity> {
match &self.phase {
SourcePhase::Loading => None,
SourcePhase::Current(publication) => Some(publication.generation()),
SourcePhase::Refreshing { retained, .. } => Some(*retained),
SourcePhase::Blocked { retained } | SourcePhase::Stopping { retained } => *retained,
}
}
pub fn retained_binding(&self) -> Option<&BindingAuthority> {
match &self.phase {
SourcePhase::Current(publication) => Some(publication.binding()),
SourcePhase::Refreshing { binding, .. } => Some(binding),
SourcePhase::Loading | SourcePhase::Blocked { .. } | SourcePhase::Stopping { .. } => {
None
}
}
}
pub fn live_publication(&self) -> Option<&CurrentPublication> {
match &self.phase {
SourcePhase::Current(publication) => Some(publication),
_ => None,
}
}
pub fn published_identity(&self) -> Option<PublicationIdentity> {
match &self.phase {
SourcePhase::Current(publication) => Some(publication.publication()),
SourcePhase::Refreshing { publication, .. } => Some(*publication),
SourcePhase::Loading | SourcePhase::Blocked { .. } | SourcePhase::Stopping { .. } => {
None
}
}
}
pub fn freeze(&mut self) -> Option<PublicationIdentity> {
let (retained, binding) = match &self.phase {
SourcePhase::Current(current) => (current.generation(), current.binding().clone()),
SourcePhase::Refreshing {
retained, binding, ..
} => (*retained, binding.clone()),
SourcePhase::Loading | SourcePhase::Blocked { .. } | SourcePhase::Stopping { .. } => {
return None;
}
};
let publication = PublicationIdentity::fresh();
self.mutation_epoch = self.mutation_epoch.advanced();
self.phase = SourcePhase::Refreshing {
retained,
binding,
publication,
};
Some(publication)
}
pub(crate) fn install(&mut self, publication: CurrentPublication) {
self.phase = SourcePhase::Current(publication);
}
pub fn request_mutation_grant(
&mut self,
input: MutationGrantInput,
) -> Result<CurrentMutationGrantAuthority, AuthorityRefusal> {
let live = match &self.phase {
SourcePhase::Current(publication) => publication.clone(),
other => {
return Err(AuthorityRefusal::PhaseNotCurrent {
phase: other.name(),
});
}
};
let presented = match input {
MutationGrantInput::LiveCurrent(presented) => presented,
other => {
return Err(AuthorityRefusal::ProvenanceNotLiveCurrent {
provenance: other.provenance(),
});
}
};
if presented != live.publication() {
return Err(AuthorityRefusal::PublicationIdentityMismatch {
presented,
live: live.publication(),
});
}
let publication = self
.freeze()
.expect("a Current source always has a publication to freeze");
let epoch = self.mutation_epoch;
self.grants_issued += 1;
Ok(CurrentMutationGrantAuthority {
authority: MutationAuthority {
generation: live.generation(),
binding: live.binding().clone(),
epoch,
publication: live.publication(),
},
published_non_current: NonCurrentPublicationProof { publication, epoch },
})
}
}