use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use arc_swap::ArcSwap;
use crate::lifecycle_identity::{
AuthorityIdentity, GenerationAuthority, ObserverToken, OperationKind, OperationReceipt,
PublicationIdentity, RetryAdvice, SourceRefusal, SourceRefusalKind,
};
#[cfg(any(test, feature = "server"))]
use crate::lifecycle_identity::GenerationIdentity;
use super::registry::ProjectKey;
#[derive(Debug)]
pub struct DarkRuntimeFactory {
root: String,
}
impl DarkRuntimeFactory {
#[cfg(any(test, feature = "server"))]
pub fn for_test_root(root: &str) -> Self {
Self {
root: root.to_string(),
}
}
pub fn project_runtime(&self, key: ProjectKey) -> ProjectIndexRuntime {
ProjectIndexRuntime {
root: self.root.clone(),
_key: key,
next_source: AtomicU64::new(1),
sources: Mutex::new(HashMap::new()),
publication: ProjectPublicationRoot {
inner: ArcSwap::new(Arc::new(ProjectRuntimePublication {
publication_identity: PublicationIdentity::fresh(),
sources: HashMap::new(),
})),
},
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SourceRuntimePhase {
Loading,
Current,
Refreshing,
Blocked,
Stopping,
Stopped,
}
#[derive(Debug)]
enum SourceRuntimeState {
Loading,
Current {
generation: Arc<VerifiedGeneration>,
},
Refreshing {
retained: Arc<VerifiedGeneration>,
permit_issued: bool,
},
Blocked {
_retained: Option<Arc<VerifiedGeneration>>,
},
Stopping {
_retained: Option<Arc<VerifiedGeneration>>,
},
}
#[derive(Debug)]
struct SourceEntry {
state: SourceRuntimeState,
tombstoned: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DarkSourceHandle(u64);
#[derive(Debug)]
pub struct VerifiedGeneration {
generation_authority: Arc<GenerationAuthority>,
complete: bool,
}
impl VerifiedGeneration {
pub fn identity(&self) -> AuthorityIdentity {
self.generation_authority.identity()
}
pub fn scope_certificate_is_complete(&self) -> bool {
self.complete
}
pub fn generation_authority(&self) -> Arc<GenerationAuthority> {
Arc::clone(&self.generation_authority)
}
}
#[derive(Debug)]
pub struct StrictLease {
generation: Arc<VerifiedGeneration>,
}
impl StrictLease {
pub fn generation(&self) -> Arc<VerifiedGeneration> {
Arc::clone(&self.generation)
}
}
#[derive(Debug)]
pub struct ProjectPublicationRoot {
inner: ArcSwap<ProjectRuntimePublication>,
}
impl ProjectPublicationRoot {
pub fn load(&self) -> Arc<ProjectRuntimePublication> {
self.inner.load_full()
}
}
#[derive(Debug)]
pub struct ProjectRuntimePublication {
publication_identity: PublicationIdentity,
sources: HashMap<u64, Arc<SourceStatePublication>>,
}
impl ProjectRuntimePublication {
pub fn publication_identity(&self) -> PublicationIdentity {
self.publication_identity
}
pub fn source_publication(
&self,
source: &DarkSourceHandle,
) -> Option<Arc<SourceStatePublication>> {
self.sources.get(&source.0).cloned()
}
}
#[derive(Debug)]
pub struct SourceStatePublication {
phase: SourceRuntimePhase,
}
impl SourceStatePublication {
pub fn phase(&self) -> SourceRuntimePhase {
self.phase
}
}
#[derive(Debug)]
pub struct SourceView {
publication_identity: PublicationIdentity,
observer_token: Option<ObserverToken>,
}
impl SourceView {
pub fn publication_identity(&self) -> PublicationIdentity {
self.publication_identity
}
pub fn observer_token(&self) -> Option<ObserverToken> {
self.observer_token
}
}
#[derive(Debug)]
pub struct DarkMutationPermit {
_sealed: (),
}
impl DarkMutationPermit {
#[cfg(any(test, feature = "server"))]
pub fn rollback_with_no_side_effect_proof_for_test(self) {}
}
#[derive(Debug)]
pub struct DarkShutdownReceipt {
_sealed: (),
}
impl DarkShutdownReceipt {
#[cfg(any(test, feature = "server"))]
pub fn wait_for_test(self) -> Result<DarkShutdownReport, SourceRefusal> {
Ok(DarkShutdownReport { joined_workers: 0 })
}
}
#[derive(Debug)]
pub struct DarkShutdownReport {
joined_workers: u64,
}
impl DarkShutdownReport {
pub fn joined_workers(&self) -> u64 {
self.joined_workers
}
}
#[derive(Debug)]
pub struct ProjectIndexRuntime {
root: String,
_key: ProjectKey,
next_source: AtomicU64,
sources: Mutex<HashMap<u64, SourceEntry>>,
publication: ProjectPublicationRoot,
}
impl ProjectIndexRuntime {
pub fn publication_root(&self) -> &ProjectPublicationRoot {
&self.publication
}
#[cfg(any(test, feature = "server"))]
pub fn admit_loading_source_for_test(&self, _name: &str) -> DarkSourceHandle {
self.insert_source(SourceRuntimeState::Loading)
}
#[cfg(any(test, feature = "server"))]
pub fn admit_current_source_for_test(&self, _name: &str) -> DarkSourceHandle {
let generation = Arc::new(VerifiedGeneration {
generation_authority: Arc::new(GenerationAuthority::captured(
AuthorityIdentity::fresh(),
GenerationIdentity::fresh(),
self.root.clone(),
)),
complete: true,
});
self.insert_source(SourceRuntimeState::Current { generation })
}
#[cfg(any(test, feature = "server"))]
pub fn begin_reload_refresh_for_test(&self, source: &DarkSourceHandle) {
self.transition(source, |state| match state {
SourceRuntimeState::Current { generation } => SourceRuntimeState::Refreshing {
retained: generation,
permit_issued: false,
},
other => other,
});
}
#[cfg(any(test, feature = "server"))]
pub fn grant_mutation_permit_for_test(
&self,
source: &DarkSourceHandle,
) -> Result<DarkMutationPermit, SourceRefusal> {
let mut granted = false;
self.transition(source, |state| match state {
SourceRuntimeState::Refreshing { retained, .. } => {
granted = true;
SourceRuntimeState::Refreshing {
retained,
permit_issued: true,
}
}
other => other,
});
if granted {
Ok(DarkMutationPermit { _sealed: () })
} else {
Err(self.refusal(OperationKind::RefreshSource, None))
}
}
#[cfg(any(test, feature = "server"))]
pub fn block_source_for_test(&self, source: &DarkSourceHandle) {
self.transition(source, |state| {
let retained = retained_of(state);
SourceRuntimeState::Blocked {
_retained: retained,
}
});
}
#[cfg(any(test, feature = "server"))]
pub fn stop_source_for_test(&self, source: &DarkSourceHandle) {
self.transition(source, |state| {
let retained = retained_of(state);
SourceRuntimeState::Stopping {
_retained: retained,
}
});
}
#[cfg(any(test, feature = "server"))]
pub fn complete_stop_for_test(&self, source: &DarkSourceHandle) {
let mut sources = self.sources.lock().expect("runtime lock");
if let Some(entry) = sources.get_mut(&source.0) {
entry.tombstoned = true;
}
drop(sources);
self.republish(Some(source.0));
}
pub fn acquire_strict(&self, source: &DarkSourceHandle) -> Result<StrictLease, SourceRefusal> {
let sources = self.sources.lock().expect("runtime lock");
let Some(entry) = sources.get(&source.0) else {
return Err(self.refusal(OperationKind::AcquireRuntime, None));
};
if entry.tombstoned {
return Err(self.refusal(OperationKind::AcquireRuntime, None));
}
match &entry.state {
SourceRuntimeState::Current { generation } => Ok(StrictLease {
generation: Arc::clone(generation),
}),
SourceRuntimeState::Refreshing {
retained,
permit_issued: false,
} => Ok(StrictLease {
generation: Arc::clone(retained),
}),
SourceRuntimeState::Refreshing {
retained,
permit_issued: true,
} => Err(self.refusal(OperationKind::AcquireRuntime, Some(retained.identity()))),
SourceRuntimeState::Loading
| SourceRuntimeState::Blocked { .. }
| SourceRuntimeState::Stopping { .. } => {
Err(self.refusal(OperationKind::AcquireRuntime, None))
}
}
}
pub fn source_phase(&self, source: &DarkSourceHandle) -> SourceRuntimePhase {
let sources = self.sources.lock().expect("runtime lock");
let Some(entry) = sources.get(&source.0) else {
return SourceRuntimePhase::Stopped;
};
if entry.tombstoned {
return SourceRuntimePhase::Stopped;
}
match &entry.state {
SourceRuntimeState::Loading => SourceRuntimePhase::Loading,
SourceRuntimeState::Current { .. } => SourceRuntimePhase::Current,
SourceRuntimeState::Refreshing { .. } => SourceRuntimePhase::Refreshing,
SourceRuntimeState::Blocked { .. } => SourceRuntimePhase::Blocked,
SourceRuntimeState::Stopping { .. } => SourceRuntimePhase::Stopping,
}
}
pub fn capture_source_view(
&self,
source: &DarkSourceHandle,
) -> Result<SourceView, SourceRefusal> {
let first = self.publication.load();
if first.source_publication(source).is_none() {
return Err(self.refusal(OperationKind::AcquireRuntime, None));
}
let revalidated = self.publication.load();
if revalidated.publication_identity() != first.publication_identity() {
return Err(self.refusal(OperationKind::AcquireRuntime, None));
}
Ok(SourceView {
publication_identity: revalidated.publication_identity(),
observer_token: None,
})
}
#[cfg(any(test, feature = "server"))]
pub fn begin_shutdown_for_test(&self) -> DarkShutdownReceipt {
DarkShutdownReceipt { _sealed: () }
}
fn insert_source(&self, state: SourceRuntimeState) -> DarkSourceHandle {
let id = self.next_source.fetch_add(1, Ordering::Relaxed);
self.sources.lock().expect("runtime lock").insert(
id,
SourceEntry {
state,
tombstoned: false,
},
);
self.republish(Some(id));
DarkSourceHandle(id)
}
fn transition(
&self,
source: &DarkSourceHandle,
apply: impl FnOnce(SourceRuntimeState) -> SourceRuntimeState,
) {
let mut sources = self.sources.lock().expect("runtime lock");
if let Some(entry) = sources.remove(&source.0) {
let next = apply(entry.state);
sources.insert(
source.0,
SourceEntry {
state: next,
tombstoned: entry.tombstoned,
},
);
}
drop(sources);
self.republish(Some(source.0));
}
fn republish(&self, changed: Option<u64>) {
let sources = self.sources.lock().expect("runtime lock");
let previous = self.publication.load();
let mut published: HashMap<u64, Arc<SourceStatePublication>> = HashMap::new();
for (id, entry) in sources.iter() {
let phase = if entry.tombstoned {
SourceRuntimePhase::Stopped
} else {
match &entry.state {
SourceRuntimeState::Loading => SourceRuntimePhase::Loading,
SourceRuntimeState::Current { .. } => SourceRuntimePhase::Current,
SourceRuntimeState::Refreshing { .. } => SourceRuntimePhase::Refreshing,
SourceRuntimeState::Blocked { .. } => SourceRuntimePhase::Blocked,
SourceRuntimeState::Stopping { .. } => SourceRuntimePhase::Stopping,
}
};
let record = match (changed, previous.sources.get(id)) {
(Some(changed_id), Some(existing)) if *id != changed_id => Arc::clone(existing),
(_, Some(existing)) if existing.phase == phase => Arc::clone(existing),
_ => Arc::new(SourceStatePublication { phase }),
};
published.insert(*id, record);
}
self.publication
.inner
.store(Arc::new(ProjectRuntimePublication {
publication_identity: PublicationIdentity::fresh(),
sources: published,
}));
}
fn refusal(&self, kind: OperationKind, evidence: Option<AuthorityIdentity>) -> SourceRefusal {
SourceRefusal::for_runtime(
SourceRefusalKind::SourceUnavailable,
OperationReceipt::for_dark_refusal(kind),
RetryAdvice::OnEvent,
evidence,
)
}
}
fn retained_of(state: SourceRuntimeState) -> Option<Arc<VerifiedGeneration>> {
match state {
SourceRuntimeState::Current { generation } => Some(generation),
SourceRuntimeState::Refreshing { retained, .. } => Some(retained),
SourceRuntimeState::Blocked { _retained } => _retained,
SourceRuntimeState::Stopping { _retained } => _retained,
SourceRuntimeState::Loading => None,
}
}