use std::any::{Any, TypeId};
use std::borrow::Cow;
use std::collections::HashSet;
use std::panic::Location;
use std::sync::Arc;
use crate::construct::Construct;
use crate::dependency::Dependencies;
use crate::graph::{BindingId, ModuleId};
use crate::key::{Key, KeyName};
use crate::module::handle::ModuleRef;
use crate::scope::ScopeKind;
use crate::transport::enhancer::{ClosureId, EnhancerSpec};
use crate::transport::handler::{HandlerInfo, HandlerSpec, Shape};
use crate::transport::inputs::Inputs;
use crate::transport::metadata::Metadata;
use crate::transport::{AnyErrorHandler, AnyGuard, AnyInterceptor, Transport};
use crate::type_name::TypeName;
#[diagnostic::on_unimplemented(
message = "`{Self}` is not a controller",
label = "a controller is declared with `#[controller]`",
note = "write `#[controller]` on `{Self}`, in place of `#[injectable]` where that is written: `#[injectable]` declares a \
type the container injects into others, and a controller is reached through its transport; a controller \
written by hand implements `ulo::Controller` as its mark and declares its handlers in `ulo::Handlers::mount`"
)]
pub trait Controller: Construct {}
#[diagnostic::on_unimplemented(
message = "`{Self}` is not a controller with handlers",
label = "a controller is declared with `#[controller]`, and its handlers with `#[handlers]`",
note = "`#[handlers]` on the impl block holding `{Self}`'s handlers writes its `Handlers` impl, and `#[controller]` on \
`{Self}`, in place of `#[injectable]` where that is written, its `Controller` mark; a controller written by \
hand implements both, declaring its handlers in `ulo::Handlers::mount`"
)]
pub trait Handlers: Controller {
fn mount(m: &mut Mount<'_>);
}
pub struct Mount<'a> {
pub(crate) handlers: &'a mut Vec<HandlerDecl>,
pub(crate) once: HashSet<TypeId>,
}
impl<'a> Mount<'a> {
pub(crate) fn new(handlers: &'a mut Vec<HandlerDecl>) -> Self {
Mount { handlers, once: HashSet::new() }
}
pub fn handler<T: Transport, H: Send + Sync + 'static>(&mut self, spec: HandlerSpec<T, H>) {
let HandlerSpec { name, handler, controller, method, meta, route, shape, dependencies } = spec;
let mut enhancer_deps = Vec::new();
controller.deps("controller", &mut enhancer_deps);
method.deps("method", &mut enhancer_deps);
self.handlers.push(HandlerDecl {
transport: TypeName::of::<T>(),
key: T::KEY,
reads_prefix: T::READS_PREFIX,
inputs: T::inputs,
name,
role_keys: [Key::of::<AnyGuard<T>, ()>(), Key::of::<AnyInterceptor<T>, ()>(), Key::of::<AnyErrorHandler<T>, ()>()],
enhancer_deps,
dependencies: Arc::new(dependencies),
route,
shape,
meta,
specs: Arc::new(Tiers { controller, method }),
handler: Arc::new(handler),
});
}
pub fn once<K: ?Sized + 'static>(&mut self, f: impl FnOnce(&mut Mount<'_>)) {
if self.once.insert(TypeId::of::<K>()) {
f(self);
}
}
}
pub struct MountedHandler<T: Transport> {
pub(crate) name: &'static str,
pub(crate) controller: KeyName,
pub(crate) module: ModuleRef,
pub(crate) controller_spec: EnhancerSpec<T>,
pub(crate) method_spec: EnhancerSpec<T>,
pub(crate) info: Arc<HandlerInfo>,
pub(crate) handler: Arc<dyn Any + Send + Sync>,
}
impl<T: Transport> MountedHandler<T> {
pub fn name(&self) -> &'static str {
self.name
}
pub fn controller(&self) -> KeyName {
self.controller
}
pub fn module(&self) -> &ModuleRef {
&self.module
}
pub fn info(&self) -> &Arc<HandlerInfo> {
&self.info
}
pub fn handler<H: 'static>(&self) -> Option<&H> {
self.handler.downcast_ref::<H>()
}
}
impl<T: Transport> Clone for MountedHandler<T> {
fn clone(&self) -> Self {
MountedHandler {
name: self.name,
controller: self.controller,
module: self.module.clone(),
controller_spec: self.controller_spec.clone(),
method_spec: self.method_spec.clone(),
info: Arc::clone(&self.info),
handler: Arc::clone(&self.handler),
}
}
}
pub struct ControllerHandle<'m> {
pub(crate) record: &'m mut ControllerRecord,
}
impl ControllerHandle<'_> {
#[track_caller]
pub fn at(self, prefix: impl Into<Cow<'static, str>>) {
self.record.prefix = Some((prefix.into(), Location::caller()));
}
}
#[derive(Clone)]
pub(crate) struct ControllerRecord {
pub(crate) binding: usize,
pub(crate) mount: fn(&mut Mount<'_>),
pub(crate) prefix: Option<(Cow<'static, str>, &'static Location<'static>)>,
}
#[derive(Clone)]
pub(crate) struct HandlerDecl {
pub(crate) transport: TypeName,
pub(crate) key: &'static str,
pub(crate) reads_prefix: bool,
pub(crate) inputs: fn(&mut Inputs),
pub(crate) name: &'static str,
pub(crate) role_keys: [Key; 3],
pub(crate) enhancer_deps: Vec<EnhancerDep>,
pub(crate) dependencies: Arc<Dependencies>,
pub(crate) route: Option<Cow<'static, str>>,
pub(crate) shape: Shape,
pub(crate) meta: Metadata,
pub(crate) specs: Arc<dyn Any + Send + Sync>,
pub(crate) handler: Arc<dyn Any + Send + Sync>,
}
#[derive(Clone)]
pub(crate) enum EnhancerDep {
Type(Key),
Closure(ClosureDep),
}
#[derive(Clone)]
pub(crate) struct ClosureDep {
pub(crate) id: ClosureId,
pub(crate) scope: ScopeKind,
pub(crate) dependencies: Arc<Dependencies>,
pub(crate) role: &'static str,
pub(crate) tier: &'static str,
pub(crate) position: usize,
pub(crate) location: &'static Location<'static>,
}
#[derive(Clone)]
pub(crate) struct HandlerRecord {
pub(crate) controller: BindingId,
pub(crate) module: ModuleId,
pub(crate) decl: HandlerDecl,
pub(crate) info: Arc<HandlerInfo>,
}
impl HandlerRecord {
pub(crate) fn new(
controller: BindingId,
controller_key: KeyName,
module: ModuleId,
prefix: Option<Cow<'static, str>>,
decl: HandlerDecl,
) -> Self {
let info = Arc::new(HandlerInfo {
transport: decl.key,
controller: controller_key,
name: decl.name,
route: decl.route.clone(),
prefix,
shape: decl.shape,
meta: decl.meta.clone(),
});
HandlerRecord { controller, module, decl, info }
}
pub(crate) fn mounted<T: Transport>(&self, module: ModuleRef, controller: KeyName) -> Option<MountedHandler<T>> {
let tiers = self.decl.specs.downcast_ref::<Tiers<T>>()?;
Some(MountedHandler {
name: self.decl.name,
controller,
module,
controller_spec: tiers.controller.clone(),
method_spec: tiers.method.clone(),
info: Arc::clone(&self.info),
handler: Arc::clone(&self.decl.handler),
})
}
}
struct Tiers<T: Transport> {
controller: EnhancerSpec<T>,
method: EnhancerSpec<T>,
}