use std::borrow::Cow;
use std::fmt;
use std::sync::Arc;
use navree_config::{Config, ModuleBuilderConfigExt};
use navree_contracts::ModuleBuilderJobsExt;
use navree_kernel::{
AppContext, BoxError, BoxFuture, CommandSpec, Contributed, Factory, Injectable, Module,
ModuleBuilder, ModuleId, PluginReport, Resolver,
};
use crate::error::Result;
use crate::events::{ClosureListener, Observer, ObserverHook};
use crate::exec::ExecContext;
use crate::global_scopes::ClosureScope;
use crate::hooks::{Flow, ModelEvent, ModelHook};
use crate::model::{Model, ModelMeta};
use crate::options::OrmOptions;
use crate::query::Builder;
use crate::record::Record;
use crate::scope::GlobalScope;
use crate::show::ModelDescription;
use crate::strict::{self, Strictness, Violation};
#[derive(Clone, Copy, Debug, Default)]
pub struct OrmModule;
impl OrmModule {
pub fn for_root(options: OrmOptions) -> ConfiguredOrmModule {
ConfiguredOrmModule {
options: Some(options),
handlers: Handlers::default(),
}
}
pub fn from_config() -> ConfiguredOrmModule {
ConfiguredOrmModule {
options: None,
handlers: Handlers::default(),
}
}
}
impl Module for OrmModule {
fn register(&self, m: &mut ModuleBuilder) {
register(m, None, Handlers::default());
}
}
#[derive(Clone)]
pub struct ConfiguredOrmModule {
options: Option<OrmOptions>,
handlers: Handlers,
}
impl ConfiguredOrmModule {
pub fn on_missing_attribute(
mut self,
handler: impl Fn(&Violation) -> Result<()> + Send + Sync + 'static,
) -> Self {
self.handlers.missing_attribute = Some(Arc::new(handler));
self
}
pub fn on_discarded_attributes(
mut self,
handler: impl Fn(&Violation) -> Result<()> + Send + Sync + 'static,
) -> Self {
self.handlers.discarded_attributes = Some(Arc::new(handler));
self
}
pub fn on_lazy_loading(
mut self,
handler: impl Fn(&Violation) -> Result<()> + Send + Sync + 'static,
) -> Self {
self.handlers.lazy_loading = Some(Arc::new(handler));
self
}
}
impl Module for ConfiguredOrmModule {
fn id(&self) -> ModuleId {
ModuleId::of::<OrmModule>()
}
fn is_configured(&self) -> bool {
true
}
fn register(&self, m: &mut ModuleBuilder) {
register(m, self.options.clone(), self.handlers.clone());
}
}
impl fmt::Debug for ConfiguredOrmModule {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ConfiguredOrmModule")
.field("options", &self.options)
.finish_non_exhaustive()
}
}
#[derive(Clone, Default)]
struct Handlers {
missing_attribute: Option<strict::ViolationHandler>,
discarded_attributes: Option<strict::ViolationHandler>,
lazy_loading: Option<strict::ViolationHandler>,
}
impl Handlers {
fn apply(self, mut strictness: Strictness) -> Strictness {
if let Some(handler) = self.missing_attribute {
strictness = strictness.on_missing_attribute(move |violation| handler(violation));
}
if let Some(handler) = self.discarded_attributes {
strictness = strictness.on_discarded_attributes(move |violation| handler(violation));
}
if let Some(handler) = self.lazy_loading {
strictness = strictness.on_lazy_loading(move |violation| handler(violation));
}
strictness
}
}
fn register(m: &mut ModuleBuilder, options: Option<OrmOptions>, handlers: Handlers) {
if options.is_none() {
m.config_section::<OrmOptions>();
}
m.global()
.factory(Factory::<OrmRuntime>::new(move |r: Resolver| {
let options = options.clone();
let handlers = handlers.clone();
async move {
let app = r.app();
let config = app.try_get::<Config>().await;
let options = match (options, &config) {
(Some(options), _) => options,
(None, Some(config)) => config.typed::<OrmOptions>()?,
(None, None) => OrmOptions::default(),
};
let environment = config.as_deref().and_then(environment);
let strictness =
handlers.apply(Strictness::from_options(&options, environment.as_deref()));
strict::install(strictness.clone());
let scopes = app.contributions::<ScopeRegistration>();
if let Some(refusal) = plugin_scope_refusal(&app, &scopes) {
return Err(BoxError::from(refusal));
}
for registration in scopes {
(registration.value.install)();
}
Ok(Arc::new(OrmRuntime {
options,
strictness,
environment,
}))
}
}))
.exports::<OrmRuntime>()
.job::<crate::broadcast::BroadcastModelEvent>()
.command(CommandSpec::new(
"model:prune",
"Prune the registered prunable models ([--model M]... [--except M]... [--chunk N] [--pretend])",
crate::prune::prune_command,
))
.command(crate::show::command());
}
fn environment(config: &Config) -> Option<String> {
config.environment().map(|env| env.to_string())
}
pub struct OrmRuntime {
options: OrmOptions,
strictness: Strictness,
environment: Option<String>,
}
impl OrmRuntime {
pub fn options(&self) -> &OrmOptions {
&self.options
}
pub fn strictness(&self) -> &Strictness {
&self.strictness
}
pub fn environment(&self) -> Option<&str> {
self.environment.as_deref()
}
}
impl fmt::Debug for OrmRuntime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OrmRuntime")
.field("options", &self.options)
.field("strictness", &self.strictness)
.field("environment", &self.environment)
.finish()
}
}
struct ScopeRegistration {
install: Box<dyn Fn() + Send + Sync>,
model: &'static str,
name: Cow<'static, str>,
}
fn plugin_scope_refusal(
app: &AppContext,
scopes: &[Contributed<ScopeRegistration>],
) -> Option<String> {
if scopes.is_empty() {
return None;
}
let plugins = app.plugins().plugins;
scopes.iter().find_map(|contributed| {
let plugin = community_plugin(&plugins, contributed.module.id)?;
let registration = &contributed.value;
let own = registration
.model
.strip_prefix(plugin.info.crate_name)
.is_some_and(|rest| rest.starts_with("::"));
if own {
return None;
}
let (name, scope, model) = (plugin.info.name, ®istration.name, registration.model);
let module = contributed.module.name;
Some(format!(
"plugin `{name}` registers the global scope `{scope}` on `{model}` in `{module}`, a model of another crate; only a module of the app registers a global scope on it: remove the plugin or update it to a version that leaves the scope to the app, and to use the plugin's scope, register it from a module of the app"
))
})
}
fn community_plugin(plugins: &[PluginReport], module: ModuleId) -> Option<&PluginReport> {
plugins.iter().find(|plugin| {
!plugin.first_party && plugin.modules.iter().any(|member| member.id == module)
})
}
type Describe =
fn(AppContext) -> BoxFuture<'static, std::result::Result<ModelDescription, BoxError>>;
#[derive(Clone, Copy)]
pub struct RegisteredModel {
meta: fn() -> &'static ModelMeta,
describe: Describe,
}
impl RegisteredModel {
pub fn of<M: Model>() -> Self {
RegisteredModel {
meta: M::meta,
describe: describe::<M>,
}
}
pub fn meta(&self) -> &'static ModelMeta {
(self.meta)()
}
pub fn name(&self) -> &'static str {
self.meta().name()
}
pub async fn describe(
&self,
app: &AppContext,
) -> std::result::Result<ModelDescription, BoxError> {
(self.describe)(app.clone()).await
}
}
impl fmt::Debug for RegisteredModel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("RegisteredModel")
.field(&self.name())
.finish()
}
}
fn describe<M: Model>(
app: AppContext,
) -> BoxFuture<'static, std::result::Result<ModelDescription, BoxError>> {
Box::pin(async move {
let registered = app.get_all::<dyn ModelHook<M>>().await?;
let app_hooks = registered.iter().map(|hook| hook.name()).collect();
Ok(ModelDescription::of::<M>(app_hooks))
})
}
pub fn registered_models(app: &AppContext) -> Vec<RegisteredModel> {
let mut models: Vec<RegisteredModel> = Vec::new();
for registration in app.contributions::<RegisteredModel>() {
let model = *registration.value;
if !models
.iter()
.any(|known| std::ptr::eq(known.meta(), model.meta()))
{
models.push(model);
}
}
models
}
pub trait ModuleBuilderOrmExt {
fn model<M: Model>(&mut self) -> &mut Self;
fn observe<M: Model>(&mut self, observer: impl Observer<M>) -> &mut Self;
fn observer<M: Model, O: Observer<M> + Injectable>(&mut self) -> &mut Self;
fn on_model<M, O>(
&mut self,
event: ModelEvent,
listener: impl for<'a> Fn(&'a mut Record<M>, &'a ExecContext) -> BoxFuture<'a, Result<O>>
+ Send
+ Sync
+ 'static,
) -> &mut Self
where
M: Model,
O: Into<Flow> + 'static;
fn global_scope<M: Model>(
&mut self,
name: impl Into<Cow<'static, str>>,
scope: impl Fn(Builder<M>) -> Builder<M> + Send + Sync + 'static,
) -> &mut Self;
fn global_scope_of<M: Model>(&mut self, scope: impl GlobalScope<M>) -> &mut Self;
}
impl ModuleBuilderOrmExt for ModuleBuilder {
fn model<M: Model>(&mut self) -> &mut Self {
self.import(OrmModule)
.contribute(RegisteredModel::of::<M>())
}
fn observe<M: Model>(&mut self, observer: impl Observer<M>) -> &mut Self {
let hook: Arc<dyn ModelHook<M>> = Arc::new(ObserverHook::new(observer));
self.multi(Factory::<dyn ModelHook<M>>::new(move |_| {
let hook = hook.clone();
async move { Ok(hook) }
}))
}
fn observer<M: Model, O: Observer<M> + Injectable>(&mut self) -> &mut Self {
self.multi(
Factory::<dyn ModelHook<M>>::new(|r: Resolver| async move {
let observer = O::construct(r).await?;
Ok(Arc::new(ObserverHook::new(observer)) as Arc<dyn ModelHook<M>>)
})
.deps(O::dependencies()),
)
}
fn on_model<M, O>(
&mut self,
event: ModelEvent,
listener: impl for<'a> Fn(&'a mut Record<M>, &'a ExecContext) -> BoxFuture<'a, Result<O>>
+ Send
+ Sync
+ 'static,
) -> &mut Self
where
M: Model,
O: Into<Flow> + 'static,
{
let hook: Arc<dyn ModelHook<M>> = Arc::new(ClosureListener::new(event, listener));
self.multi(Factory::<dyn ModelHook<M>>::new(move |_| {
let hook = hook.clone();
async move { Ok(hook) }
}))
}
fn global_scope<M: Model>(
&mut self,
name: impl Into<Cow<'static, str>>,
scope: impl Fn(Builder<M>) -> Builder<M> + Send + Sync + 'static,
) -> &mut Self {
self.global_scope_of::<M>(ClosureScope::new(name, scope))
}
fn global_scope_of<M: Model>(&mut self, scope: impl GlobalScope<M>) -> &mut Self {
let name = scope.name();
let scope: Arc<dyn GlobalScope<M>> = Arc::new(scope);
self.import(OrmModule).contribute(ScopeRegistration {
install: Box::new(move || crate::global_scopes::register::<M>(scope.clone())),
model: std::any::type_name::<M>(),
name,
})
}
}