use std::fmt;
#[cfg(debug_assertions)]
use std::sync::Arc;
use laravel::config::{Config, Env, Section};
use laravel::foundation::ServiceProvider;
#[cfg(debug_assertions)]
use crate::gate::AnyGate;
use crate::gate::DevtoolsGate;
#[derive(Clone, Section)]
#[non_exhaustive]
pub struct DevtoolsConfig {
#[env("DEVTOOLS_ENABLED")]
pub enabled: Option<bool>,
#[env("DEVTOOLS_ERROR_TEXT", default = false)]
pub error_text: bool,
#[env("DEVTOOLS_KEY")]
pub key: Option<String>,
#[env("DEVTOOLS_LOCAL", default = true)]
pub local: bool,
}
impl fmt::Debug for DevtoolsConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DevtoolsConfig")
.field("enabled", &self.enabled)
.field("error_text", &self.error_text)
.field("key", &self.key.as_ref().map(|_| "[masked]"))
.field("local", &self.local)
.finish()
}
}
#[derive(Clone, Default)]
#[must_use]
pub struct DevtoolsServiceProvider {
#[cfg(debug_assertions)]
gate: Option<Arc<dyn AnyGate>>,
#[cfg(debug_assertions)]
crates: Vec<String>,
}
impl DevtoolsServiceProvider {
pub fn new() -> Self {
Self::default()
}
pub fn with_gate(self, gate: impl DevtoolsGate) -> Self {
#[cfg(debug_assertions)]
{
Self {
gate: Some(Arc::new(gate)),
..self
}
}
#[cfg(not(debug_assertions))]
{
drop(gate);
self
}
}
pub fn with_crates<I>(self, crates: I) -> Self
where
I: IntoIterator,
I::Item: Into<String>,
{
#[cfg(debug_assertions)]
{
let mut provider = self;
provider.crates.extend(crates.into_iter().map(Into::into));
provider
}
#[cfg(not(debug_assertions))]
{
drop(crates);
self
}
}
}
impl fmt::Debug for DevtoolsServiceProvider {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut debug = f.debug_struct("DevtoolsServiceProvider");
#[cfg(debug_assertions)]
debug.field("gate", &self.gate.as_ref().map(|_| "[set]"));
#[cfg(debug_assertions)]
debug.field("crates", &self.crates);
debug.finish()
}
}
impl ServiceProvider for DevtoolsServiceProvider {
fn config(&self, config: &mut Config, env: &Env) {
config.discover(env!("CARGO_CRATE_NAME"), env);
}
#[cfg(debug_assertions)]
fn register(&self, app: &mut laravel::container::Registrar) {
debug::register(app, self.gate.clone(), &self.crates);
}
#[cfg(debug_assertions)]
fn boot(&self, app: &laravel::container::Container) -> impl Future<Output = laravel::Result<()>> + Send {
std::future::ready(debug::boot(app.config()))
}
}
#[cfg(debug_assertions)]
mod debug {
use std::fmt;
use laravel::config::Config;
use laravel::config::app::Environment;
use laravel::container::Registrar;
use super::{Arc, DevtoolsConfig};
use crate::collector::Collector;
use crate::file_store::FileStore;
use crate::gate::AnyGate;
use crate::http::Access;
use crate::store::Store;
const KEY_LENGTH: std::ops::RangeInclusive<usize> = 32..=laravel::hash::MAX_PASSWORD_BYTES;
pub(super) fn register(app: &mut Registrar, gate: Option<Arc<dyn AnyGate>>, crates: &[String]) {
let config = app.config();
if !runs(config) {
return;
}
let section = config.section::<DevtoolsConfig>();
let store = Arc::new(FileStore::new(config.app.storage_path("devtools")));
let collector = Collector::shared(Arc::clone(&store) as Arc<dyn Store>)
.with_error_text(section.error_text)
.with_crates(crates.iter().cloned());
let access = Access::new(section.key.as_deref(), section.local, gate);
crate::http::register(app, store, collector.key(), access);
app.logging().layer(collector);
}
pub(super) fn boot(config: &Config) -> laravel::Result<()> {
let environment = &config.app.env;
let section = config.section::<DevtoolsConfig>();
let asked = section.enabled == Some(true);
if asked && !matches!(environment, Environment::Local | Environment::Testing) {
return Err(EnabledOutsideLocal(environment.as_str().to_owned()).into());
}
let key = section.key.as_deref();
if runs(config) && key.is_some_and(|key| !KEY_LENGTH.contains(&key.len())) {
return Err(KeyLength.into());
}
Ok(())
}
fn runs(config: &Config) -> bool {
config.app.env.is_local() && config.section::<DevtoolsConfig>().enabled != Some(false)
}
#[derive(Debug)]
struct EnabledOutsideLocal(String);
impl fmt::Display for EnabledOutsideLocal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"DEVTOOLS_ENABLED=true, but the developer tools only run with APP_ENV=local, and \
this application runs with APP_ENV={}{}. Remove DEVTOOLS_ENABLED or set it to false.",
self.0,
if self.0 == "production" {
" (also what an unset APP_ENV means)"
} else {
""
}
)
}
}
impl std::error::Error for EnabledOutsideLocal {}
#[derive(Debug)]
struct KeyLength;
impl fmt::Display for KeyLength {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"DEVTOOLS_KEY must be between {} and {} bytes long. Generate one with \
`openssl rand -hex 24`.",
KEY_LENGTH.start(),
KEY_LENGTH.end()
)
}
}
impl std::error::Error for KeyLength {}
}