use std::any::{TypeId, type_name};
use std::marker::PhantomData;
use std::sync::atomic::Ordering;
use std::sync::{Arc, OnceLock};
use crate::app::shared::AppShared;
use crate::binding::{Coercion, Instance, Recipe, downcast_instance};
use crate::dependency::{Dep, Ext, Many, Read, ReadKind};
use crate::error::{FailureReason, LookupError, LookupKind, Permanent, UndeclaredRead};
use crate::error::UndeclaredWhat;
use crate::redact::redact;
use crate::execution::{ExecShared, ExecutionRef};
use crate::graph::{BindingId, Graph, ModuleId, Visible};
use crate::key::{BindingKind, Key};
use crate::module::handle::ModuleRef;
use crate::type_name::TypeName;
pub struct Resolver<'a> {
pub(crate) app: &'a Arc<AppShared>,
pub(crate) graph: Arc<Graph>,
pub(crate) module: ModuleId,
pub(crate) exec: Option<&'a Arc<ExecShared>>,
pub(crate) purpose: Purpose,
reading: OnceLock<Arc<Reading>>,
violation: OnceLock<UndeclaredRead>,
}
pub(crate) struct Reading {
reader: Key,
declared: Vec<Read>,
}
impl Reading {
pub(crate) fn of<T: crate::construct::Construct>() -> Self {
let mut d = crate::dependency::Dependencies::default();
T::dependencies(&mut d);
let declared = d.list.iter().flat_map(|record| record.requirement.reads.iter().copied()).collect();
Reading { reader: Key::of::<T, ()>(), declared }
}
fn declares(&self, wanted: Wanted) -> bool {
self.declared.iter().any(|read| match (read.kind, wanted) {
(ReadKind::Single(a), Wanted::Single(b)) | (ReadKind::Collection(a), Wanted::Collection(b)) => a == b,
(ReadKind::Extension(a), Wanted::Extension(b)) => a == b.id(),
(ReadKind::Execution, Wanted::Execution) => true,
_ => false,
})
}
}
#[derive(Clone, Copy)]
enum Wanted {
Single(Key),
Collection(Key),
Extension(TypeName),
Execution,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Purpose {
Lookup,
Lifecycle,
}
impl<'a> Resolver<'a> {
pub(crate) fn new(
app: &'a Arc<AppShared>,
module: ModuleId,
exec: Option<&'a Arc<ExecShared>>,
purpose: Purpose,
) -> Self {
Resolver { app, graph: app.graph(), module, exec, purpose, reading: OnceLock::new(), violation: OnceLock::new() }
}
pub(crate) fn in_module(&self, module: ModuleId) -> Resolver<'a> {
Resolver {
app: self.app,
graph: Arc::clone(&self.graph),
module,
exec: self.exec,
purpose: self.purpose,
reading: OnceLock::new(),
violation: OnceLock::new(),
}
}
pub(crate) fn without_execution(&self) -> Resolver<'a> {
Resolver {
app: self.app,
graph: Arc::clone(&self.graph),
module: self.module,
exec: None,
purpose: self.purpose,
reading: self.reading.clone(),
violation: OnceLock::new(),
}
}
pub(crate) fn arm(&self, reading: Arc<Reading>) -> Result<(), Arc<Reading>> {
self.reading.set(reading)
}
pub(crate) fn take_violation(&self) -> Option<UndeclaredRead> {
self.violation.get().cloned()
}
fn declared(&self, wanted: Wanted) -> Result<(), LookupError> {
let Some(reading) = self.reading.get() else { return Ok(()) };
if reading.declares(wanted) {
return Ok(());
}
let what = match wanted {
Wanted::Single(key) => UndeclaredWhat::Key(key.name(BindingKind::Single)),
Wanted::Collection(key) => UndeclaredWhat::Key(key.name(BindingKind::Collection)),
Wanted::Extension(name) => UndeclaredWhat::Extension(name),
Wanted::Execution => UndeclaredWhat::Execution,
};
let refusal = UndeclaredRead::new(reading.reader.type_name(), what);
let _ = self.violation.set(refusal.clone());
let error = redact(&self.graph.secrets, Box::new(Permanent::new(refusal)));
Err(LookupError::Construct { key: reading.reader.name(BindingKind::Single), reason: FailureReason::Errored(error) })
}
pub(crate) async fn instance(&self, id: BindingId) -> Result<Instance, LookupError> {
self.app.obtain(self, id).await
}
pub async fn dep<T: ?Sized + Send + Sync + 'static>(&self) -> Result<Dep<T>, LookupError> {
self.dep_qualified::<T, ()>().await
}
pub async fn dep_qualified<T: ?Sized + Send + Sync + 'static, Q: 'static>(&self) -> Result<Dep<T, Q>, LookupError> {
self.single::<T>(Key::of::<T, Q>()).await.map(Dep::from_arc)
}
pub async fn many<T: ?Sized + Send + Sync + 'static>(&self) -> Result<Many<T>, LookupError> {
self.many_qualified::<T, ()>().await
}
pub async fn many_qualified<T: ?Sized + Send + Sync + 'static, Q: 'static>(&self) -> Result<Many<T, Q>, LookupError> {
let key = Key::of::<T, Q>();
self.declared(Wanted::Collection(key))?;
let ids = self.contributions(key)?;
let mut items = Vec::with_capacity(ids.len());
for &id in ids.iter() {
let instance = self.instance(id).await?;
let item = self.widen::<T>(id, &instance).ok_or_else(|| wrong_type::<T>(key, BindingKind::Collection))?;
items.push(item);
}
Ok(Many::from_items(items.into()))
}
pub fn entries<T: ?Sized + Send + Sync + 'static>(&self) -> Result<Entries<'_, T>, LookupError> {
let key = Key::of::<T, ()>();
self.declared(Wanted::Collection(key))?;
let ids = self.contributions(key)?;
Ok(Entries { resolver: self, ids, next: 0, _t: PhantomData })
}
pub fn ext<T: Send + Sync + 'static>(&self) -> Result<Ext<T>, LookupError> {
let key = Key::of::<T, ()>();
self.declared(Wanted::Extension(TypeName::of::<T>()))?;
let exec = self.exec_for(key)?;
exec.extensions.get::<T>().map(Ext::from_arc).ok_or_else(|| not_found(key, LookupKind::Extension))
}
pub fn input<T: Send + Sync + 'static>(&self) -> Result<Dep<T>, LookupError> {
let key = Key::of::<T, ()>();
self.declared(Wanted::Single(key))?;
let exec = self.exec_for(key)?;
exec.inputs.get::<T>().map(Dep::from_arc).ok_or_else(|| not_found(key, LookupKind::Input))
}
pub fn module(&self) -> ModuleRef {
let exec = self.exec.map(|shared| ExecutionRef { shared: Arc::clone(shared) });
ModuleRef::new(Arc::clone(self.app), self.module, exec)
}
pub fn execution(&self) -> Result<ExecutionRef, LookupError> {
self.declared(Wanted::Execution)?;
let shared = self.exec_for(Key::of::<ExecutionRef, ()>())?;
Ok(ExecutionRef { shared: Arc::clone(shared) })
}
pub async fn by_key<T: ?Sized + Send + Sync + 'static>(&self, key: Key) -> Result<Arc<T>, LookupError> {
self.single::<T>(key).await
}
async fn single<T: ?Sized + Send + Sync + 'static>(&self, key: Key) -> Result<Arc<T>, LookupError> {
self.declared(Wanted::Single(key))?;
let found = self.locate(key)?;
if key.type_id() != TypeId::of::<T>() {
return Err(wrong_type::<T>(key, BindingKind::Single));
}
match found {
Found::Binding(id) => {
let instance = self.instance(id).await?;
self.widen::<T>(id, &instance).ok_or_else(|| wrong_type::<T>(key, BindingKind::Single))
}
Found::Input(input) => self.seeded::<T>(input),
}
}
fn locate(&self, key: Key) -> Result<Found, LookupError> {
match self.graph.lookup(self.module, key) {
Some(Visible::Binding(id)) => Ok(Found::Binding(*id)),
Some(Visible::Input(input)) => Ok(Found::Input(*input)),
Some(Visible::Ambiguous(sources)) => Err(LookupError::Ambiguous {
key: key.name(BindingKind::Single),
sources: sources.iter().map(|(module, _)| self.graph.module(*module).name.clone()).collect(),
}),
None if !self.graph.collection(key).is_empty() => Err(LookupError::WrongKind {
key: key.name(BindingKind::Collection),
expected: BindingKind::Single,
found: BindingKind::Collection,
}),
None => Err(not_found(key, LookupKind::Binding)),
}
}
fn contributions(&self, key: Key) -> Result<Arc<[BindingId]>, LookupError> {
let ids = self.graph.collection(key);
if ids.is_empty() && self.graph.lookup(self.module, key).is_some() {
return Err(LookupError::WrongKind {
key: key.name(BindingKind::Single),
expected: BindingKind::Collection,
found: BindingKind::Single,
});
}
Ok(ids)
}
fn seeded<T: ?Sized + Send + Sync + 'static>(&self, input: Key) -> Result<Arc<T>, LookupError> {
let exec = self.exec_for(input)?;
let erased = exec.inputs.get_erased(input.type_id()).ok_or_else(|| not_found(input, LookupKind::Input))?;
downcast_instance::<T>(&erased).ok_or_else(|| wrong_type::<T>(input, BindingKind::Single))
}
fn exec_for(&self, key: Key) -> Result<&'a Arc<ExecShared>, LookupError> {
let exec = self.exec.ok_or(LookupError::ExecutionRequired { key: key.name(BindingKind::Single) })?;
if exec.ended.load(Ordering::Acquire) {
return Err(LookupError::ExecutionEnded { key: key.name(BindingKind::Single) });
}
Ok(exec)
}
fn widen<T: ?Sized + Send + Sync + 'static>(&self, id: BindingId, instance: &Instance) -> Option<Arc<T>> {
if let Some(arc) = downcast_instance::<T>(instance) {
return Some(arc);
}
let coerce = self.coercion_to(id, TypeId::of::<T>())?;
downcast_instance::<T>(&coerce(instance))
}
fn coercion_to(&self, mut id: BindingId, ty: TypeId) -> Option<&Coercion> {
for _ in 0..self.graph.bindings.len() {
let binding = self.graph.binding(id);
let record = &binding.record;
if record.primary.type_id() == ty {
if let Some(coerce) = &record.into_primary {
return Some(coerce);
}
}
if let Some(also) = record.also.iter().find(|also| also.key.type_id() == ty) {
return Some(&also.coerce);
}
let Recipe::Alias { target } = &record.recipe else { return None };
match self.graph.lookup(binding.origin, *target) {
Some(Visible::Binding(next)) => id = *next,
_ => return None,
}
}
None
}
}
#[derive(Clone, Copy)]
enum Found {
Binding(BindingId),
Input(Key),
}
fn not_found(key: Key, kind: LookupKind) -> LookupError {
LookupError::NotFound { key: key.name(BindingKind::Single), kind }
}
fn wrong_type<T: ?Sized>(key: Key, kind: BindingKind) -> LookupError {
LookupError::WrongType { key: key.name(kind), requested: type_name::<T>() }
}
pub struct Entries<'r, T: ?Sized> {
pub(crate) resolver: &'r Resolver<'r>,
pub(crate) ids: Arc<[BindingId]>,
pub(crate) next: usize,
pub(crate) _t: PhantomData<fn() -> Box<T>>,
}
impl<'r, T: ?Sized + Send + Sync + 'static> Iterator for Entries<'r, T> {
type Item = Entry<'r, T>;
fn next(&mut self) -> Option<Entry<'r, T>> {
let id = *self.ids.get(self.next)?;
self.next += 1;
Some(Entry { resolver: self.resolver, id, _t: PhantomData })
}
fn size_hint(&self) -> (usize, Option<usize>) {
let left = self.ids.len() - self.next;
(left, Some(left))
}
}
impl<T: ?Sized + Send + Sync + 'static> ExactSizeIterator for Entries<'_, T> {}
pub struct Entry<'r, T: ?Sized> {
pub(crate) resolver: &'r Resolver<'r>,
pub(crate) id: BindingId,
pub(crate) _t: PhantomData<fn() -> Box<T>>,
}
impl<T: ?Sized + Send + Sync + 'static> Entry<'_, T> {
pub async fn resolve(&self) -> Result<Arc<T>, LookupError> {
let instance = self.resolver.instance(self.id).await?;
self.resolver
.widen::<T>(self.id, &instance)
.ok_or_else(|| wrong_type::<T>(Key::of::<T, ()>(), BindingKind::Collection))
}
}