mod boot;
mod commands;
mod connections;
mod console;
mod inspiring;
pub(crate) use crate::console::signals::shutdown_signal;
mod kernel;
pub(crate) mod logging;
#[cfg(feature = "opentelemetry")]
pub(crate) mod opentelemetry;
mod provider;
mod providers;
pub(crate) use laravel_core::foundation::{cloud, shutdown, telemetry};
use crate::cache::CacheManagerInternals as _;
use crate::console::ConsoleInternals as _;
use crate::schedule::ScheduleInternals as _;
use std::future::Future;
use std::path::Path;
use std::process::ExitCode;
use std::sync::{Arc, Mutex, Weak};
use futures_util::FutureExt;
pub(crate) use self::boot::Boot;
pub use self::inspiring::Inspiring;
use self::kernel::Kernel;
pub(crate) use self::kernel::RecordRoot;
pub use self::logging::{LogGuard, LogLayers, LoggingError};
pub use self::provider::{Providers, ServiceProvider};
pub(crate) use self::shutdown::Shutdown;
use crate::cache::CacheManager;
use crate::clock::Clock;
use crate::config::{Config, Env, EnvInternals as _, InvalidEnv};
use crate::console::{Commands, CommandsInternals as _};
use crate::container::{CallbackResult, Container, Inject, Registrar, Services};
use crate::context::{App, Context, Internals};
use crate::crypt::{Cipher, Encrypter, KeyError};
use crate::error::Result;
use crate::errors::{ErrorHandler, Errors, ResponseBoundary};
use crate::event::Dispatcher;
use crate::head::HeadConfig;
use crate::http::MiddlewareConfig;
use crate::queue::QueueManagerInternals as _;
use crate::routing::assets::Assets;
use crate::routing::{RouteTable, Routing, table};
use crate::schedule::Schedule;
use crate::task::Ticks;
use crate::view::{ViewConfig, ViewConfigInternals as _};
#[doc(inline)]
pub use laravel_core::foundation::Host;
#[must_use]
#[track_caller]
pub fn host() -> Option<Host> {
Context::expect("laravel::foundation::host()").host().cloned()
}
#[derive(Debug, Clone)]
pub struct Application {
router: axum::Router,
shared: Arc<App>,
providers: Providers,
log_layers: Arc<Mutex<Option<LogLayers>>>,
dotenv: DotEnv,
}
impl Application {
pub fn configure() -> ApplicationBuilder {
ApplicationBuilder {
env: None,
env_vars: Vec::new(),
config_files: Vec::new(),
registrations: Vec::new(),
booted: Vec::new(),
providers: Providers::default(),
framework_providers: provider::framework(),
}
}
pub async fn boot(&self) -> Result<()> {
self.shared.part::<Boot>().run().await
}
pub async fn scope<T>(&self, callback: impl AsyncFnOnce() -> T) -> T {
self.boot_or_panic().await;
Context::new(Arc::clone(&self.shared), None).scope(callback()).await
}
pub async fn resolve<T: ?Sized + Send + Sync + 'static>(&self) -> Inject<T> {
self.boot_or_panic().await;
match self.shared.services.resolve().await.map(Inject::from) {
Ok(service) => service,
Err(error) => panic!("{error:#}"),
}
}
pub async fn tick(&self, name: &str) -> crate::Result<()> {
self.boot_or_panic().await;
match crate::task::ticks::run_named(&self.shared, name).await {
Some(result) => result,
None => panic!("no tick is named `{name}`"),
}
}
#[must_use]
pub fn host(&self) -> Option<Host> {
self.shared.host.get().cloned()
}
async fn boot_or_panic(&self) {
if let Err(error) = self.boot().await {
panic!("the application failed to boot: {error:#}");
}
}
#[must_use]
pub const fn providers(&self) -> &Providers {
&self.providers
}
#[must_use]
pub fn routes(&self) -> &RouteTable {
self.shared.part()
}
#[must_use]
pub fn config(&self) -> &Config {
&self.shared.config
}
pub(crate) fn services(&self) -> &Services {
&self.shared.services
}
pub(crate) fn clock(&self) -> &Clock {
&self.shared.clock
}
#[cfg(feature = "database")]
pub(crate) fn seed_faker_default(&self, name: &str) {
self.shared.part::<crate::model::Factories>().seed_faker_default(name);
}
#[cfg(feature = "inertia")]
pub(crate) fn head(&self) -> &HeadConfig {
self.shared.part()
}
#[cfg(test)]
pub(crate) fn begin_shutdown(&self) {
self.shared.shutdown.begin();
}
#[cfg(test)]
pub(crate) fn cut_off_requests(&self) {
self.shared.shutdown.cut_off();
}
pub fn encrypter(&self) -> Result<&Encrypter, KeyError> {
self.shared.encrypter.as_ref().map_err(Clone::clone)
}
pub fn into_router(self) -> axum::Router {
self.router
}
pub(crate) const fn router(&self) -> &axum::Router {
&self.router
}
pub(crate) fn check_auth_pages(&self) -> Result<(), StartupError> {
match self.shared.part::<AuthProblems>().0.as_slice() {
[] => Ok(()),
problems => Err(StartupError::Auth(problems.to_vec())),
}
}
}
type DotEnv = Arc<[(String, String)]>;
type ConfigFile = Box<dyn FnOnce(&mut Config, &Env)>;
type Registration = Box<dyn FnOnce(&mut Registrar, &Config)>;
#[must_use = "an application builder does nothing until `.create()` is called"]
pub struct ApplicationBuilder {
env: Option<Env>,
env_vars: Vec<(String, String)>,
config_files: Vec<ConfigFile>,
registrations: Vec<Registration>,
booted: Vec<boot::Booted>,
providers: Providers,
framework_providers: Providers,
}
impl ApplicationBuilder {
pub fn replace_env(mut self, env: Env) -> Self {
self.env = Some(env);
self
}
pub fn for_testing(self, base_path: impl AsRef<Path>) -> Self {
let base_path = base_path.as_ref();
let mut env = Env::from_testing_dir(base_path);
env.set(vec![
("APP_ENV".to_owned(), "testing".to_owned()),
("APP_BASE_PATH".to_owned(), base_path.to_string_lossy().into_owned()),
]);
if !env.is_set("APP_KEY") {
env.set(vec![("APP_KEY".to_owned(), Encrypter::generate_key(Cipher::Aes256Cbc))]);
}
env.set_fallbacks([
("APP_DEBUG", "true"),
("BCRYPT_ROUNDS", "4"),
("BROADCAST_CONNECTION", "discard"),
("CACHE_STORE", "memory"),
("FEATURE_STORE", "memory"),
("INERTIA_SSR", "false"),
("MAIL_MAILER", "log"),
("OTEL_SDK_DISABLED", "true"),
("QUEUE_CONNECTION", "sync"),
("SESSION_DRIVER", "memory"),
("SMS_SENDER", "log"),
("WORKFLOW_STORE", "memory"),
]);
self.replace_env(env)
}
pub fn with_env(self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.with_envs([(key, value)])
}
pub fn with_envs<K: Into<String>, V: Into<String>>(mut self, vars: impl IntoIterator<Item = (K, V)>) -> Self {
self.env_vars
.extend(vars.into_iter().map(|(key, value)| (key.into(), value.into())));
self
}
pub fn with_config(mut self, configure: impl FnOnce(&mut Config, &Env) + 'static) -> Self {
self.config_files.push(Box::new(configure));
self
}
pub fn with_providers(mut self, configure: impl FnOnce(&mut Providers)) -> Self {
configure(&mut self.providers);
self
}
pub fn with_services(self, register: impl FnOnce(&mut Registrar) + 'static) -> Self {
self.registration(|app, _| register(app))
}
pub fn with_events(self, configure: impl FnOnce(&mut Dispatcher, &Config) + 'static) -> Self {
self.registration(|app, config| configure(app.events(), config))
}
pub fn with_auth(self, configure: impl FnOnce(&mut crate::auth::AuthConfig, &Config) + 'static) -> Self {
self.registration(|app, config| configure(&mut app.auth, config))
}
pub fn booted<F, Fut, R>(mut self, booted: F) -> Self
where
F: FnOnce(Container) -> Fut + Send + 'static,
Fut: Future<Output = R> + Send + 'static,
R: CallbackResult + 'static,
{
self.booted
.push(Box::new(|app| Box::pin(booted(app).map(CallbackResult::into_result))));
self
}
pub fn with_routing(self, configure: impl FnOnce(&mut Routing, &Config) + 'static) -> Self {
self.registration(|app, config| configure(app.routing(), config))
}
pub fn with_middleware(self, configure: impl FnOnce(&mut MiddlewareConfig, &Config) + 'static) -> Self {
self.registration(|app, config| configure(app.middleware(), config))
}
pub fn with_logging(self, configure: impl FnOnce(&mut LogLayers, &Config) + 'static) -> Self {
self.registration(|app, config| configure(app.logging(), config))
}
pub fn with_views(self, configure: impl FnOnce(&mut ViewConfig, &Config) + 'static) -> Self {
self.registration(|app, config| configure(app.views(), config))
}
pub fn with_errors(self, configure: impl FnOnce(&mut Errors, &Config) + 'static) -> Self {
self.registration(|app, config| configure(app.errors(), config))
}
pub fn with_head(self, configure: impl FnOnce(&mut HeadConfig, &Config) + 'static) -> Self {
self.registration(|app, config| configure(app.head(), config))
}
pub fn with_commands(self, configure: impl FnOnce(&mut Commands, &Config) + 'static) -> Self {
self.registration(|app, config| configure(app.commands(), config))
}
#[cfg(feature = "database")]
pub fn with_seeders(self, configure: impl FnOnce(&mut crate::db::Seeders, &Config) + 'static) -> Self {
self.registration(|app, config| configure(&mut app.seeders, config))
}
pub fn with_schedule(self, configure: impl FnOnce(&mut Schedule, &Config) + 'static) -> Self {
self.registration(|app, config| configure(app.schedule(), config))
}
pub fn with_ticks(self, configure: impl FnOnce(&mut Ticks, &Config) + 'static) -> Self {
self.registration(|app, config| configure(app.ticks(), config))
}
#[cfg(feature = "database")]
pub fn with_migrations(self, migrations: crate::db::Migrations) -> Self {
self.registration(|app, _| {
app.migrations().add(migrations);
})
}
#[cfg(feature = "database")]
pub fn with_schema(self, dumps: crate::db::SchemaDumps) -> Self {
self.registration(|app, _| {
app.instance(dumps);
})
}
#[cfg(feature = "database")]
pub fn refresh_database(self) -> Self {
self.registration(|app, _| {
app.instance(crate::db::migrations::refresh::RefreshDatabase);
})
}
#[cfg(feature = "database")]
pub fn seed<S, F>(self, seeder: S) -> Self
where
S: FnOnce() -> F + Send + 'static,
F: Future<Output = Result<()>> + Send + 'static,
{
self.booted(move |app| async move {
let manager = app.resolve::<crate::db::DatabaseManager>().await?;
crate::db::seeders::seed_test(&manager, Box::pin(seeder())).await
})
}
#[cfg(feature = "database")]
#[track_caller]
pub fn seed_once<S, F>(self, seeder: S) -> Self
where
S: Fn() -> F,
F: Future<Output = Result<()>>,
{
let Some(seeder) = crate::db::seeders::registered(&seeder) else {
panic!(
"`seed_once` takes a function marked `#[seeder]`, not `{}`",
std::any::type_name::<S>()
);
};
self.registration(move |app, _| {
app.instance(crate::db::seeders::SeedOnce(seeder));
})
}
fn registration(mut self, register: impl FnOnce(&mut Registrar, &Config) + 'static) -> Self {
self.registrations.push(Box::new(register));
self
}
#[must_use = "return the exit code from `main`, or the process exits with status 0 when startup fails"]
pub fn run(self) -> ExitCode {
match self.try_create() {
Ok(application) => application.run(),
Err(error) => {
crate::console::Console::terminal().error(error.to_string());
ExitCode::FAILURE
}
}
}
#[track_caller]
pub fn create(self) -> Application {
match self.try_create() {
Ok(application) => application,
Err(error) => panic!("{error}"),
}
}
pub fn try_create(self) -> Result<Application, StartupError> {
crate::errors::panic::capture_locations();
crate::tls::install_crypto_provider();
let Self {
env,
env_vars,
config_files,
registrations,
booted,
providers: application_providers,
framework_providers: mut providers,
} = self;
providers.extend(application_providers.clone());
let mut env = env.unwrap_or_else(Env::from_process);
env.set(env_vars);
let (config, dotenv) = read_config(env, config_files, &providers)?;
let registered = register(registrations, &providers, &config)?;
assemble(registered, providers, application_providers, booted, config, dotenv)
}
}
fn read_config(
mut env: Env,
config_files: Vec<ConfigFile>,
providers: &Providers,
) -> Result<(Arc<Config>, DotEnv), StartupError> {
let mut config = Config::from_env(&env);
for provider in providers.iter() {
provider.provider.config(&mut config, &env);
}
config.discover("app", &env);
for configure in config_files {
configure(&mut config, &env);
}
config.validate_env(&env)?;
if let Some(destination) = config.logging.duplicate_destination() {
return Err(StartupError::DuplicateLogChannel(destination.name()));
}
Ok((Arc::new(config), env.take_dotenv().into()))
}
fn register(
registrations: Vec<Registration>,
providers: &Providers,
config: &Arc<Config>,
) -> Result<Registered, StartupError> {
let mut registrar = Registrar::new(Arc::clone(config));
for provider in providers.iter() {
registrar.provider(Some(provider.name));
provider.provider.register(&mut registrar);
}
registrar.provider(None);
registrar.discover("app");
registrar.auth.discover("app");
#[cfg(feature = "database")]
registrar.seeders.discover("app");
for register in registrations {
register(&mut registrar, config);
}
if !registrar.services.conflicts.is_empty() {
return Err(StartupError::Services(std::mem::take(
&mut registrar.services.conflicts,
)));
}
let (auth, auth_problems) = std::mem::take(&mut registrar.auth)
.finish()
.map_err(StartupError::Auth)?;
let auth_pages = auth.pages;
let auth = Arc::new(auth);
registrar.instance_as::<dyn crate::http::identity::Identify>(Arc::clone(&auth) as _);
registrar.instance_as(auth);
#[cfg(feature = "database")]
crate::session::database::validate(&config.session).map_err(|error| StartupError::Session(error.to_string()))?;
std::mem::take(&mut registrar.sessions)
.register(&mut registrar.services)
.map_err(|error| StartupError::Session(error.to_string()))?;
std::mem::take(&mut registrar.features)
.register(&mut registrar.services)
.map_err(|error| StartupError::Features(error.to_string()))?;
let cache_drivers = std::mem::take(&mut registrar.cache)
.register(®istrar.services)
.map_err(|error| StartupError::Cache(error.to_string()))?;
#[cfg(feature = "search")]
{
let settings = config
.get::<crate::config::search::Search>()
.cloned()
.unwrap_or_default();
let engines = laravel_search::search::engines(std::mem::take(&mut registrar.search), &settings)
.map_err(|error| StartupError::Search(error.to_string()))?;
registrar.part(engines);
}
let queue_drivers = std::mem::take(&mut registrar.queue)
.register(®istrar.services)
.map_err(StartupError::Queue)?;
crate::queue::validate(&config.queue).map_err(StartupError::Queue)?;
let workflow_drivers = std::mem::take(&mut registrar.workflow)
.register(config)
.map_err(StartupError::Workflow)?;
crate::broadcast::validate(config).map_err(StartupError::Broadcast)?;
let mail_drivers = std::mem::take(&mut registrar.mail)
.register(config)
.map_err(StartupError::Mail)?;
crate::sms::validate(config).map_err(StartupError::Sms)?;
let social = std::mem::take(&mut registrar.social).build(config);
registrar.part(social);
crate::hash::valid_rounds(config.hashing.rounds).map_err(StartupError::Hashing)?;
registrar.commands.validate().map_err(StartupError::Commands)?;
let schedule = std::mem::take(&mut registrar.schedule);
registrar.instance(schedule);
registrar.ticks.validate().map_err(StartupError::Ticks)?;
let ticks = std::mem::take(&mut registrar.ticks);
registrar.instance(ticks);
#[cfg(feature = "database")]
register_database(&mut registrar, config)?;
let events = std::mem::take(&mut registrar.events);
registrar.instance(events);
Ok(Registered {
registrar,
auth_pages,
auth_problems,
cache: cache_drivers,
mail: mail_drivers,
queue: queue_drivers,
workflow: workflow_drivers,
})
}
#[cfg(feature = "database")]
fn register_database(registrar: &mut Registrar, config: &Config) -> Result<(), StartupError> {
let migrations = std::mem::take(&mut registrar.migrations);
migrations.validate().map_err(StartupError::Migrations)?;
registrar.instance(migrations);
if !registrar.is_bound::<crate::db::SchemaDumps>() {
registrar.instance(crate::db::SchemaDumps::default());
}
let refreshes = registrar.is_bound::<crate::db::migrations::refresh::RefreshDatabase>();
if refreshes && config.app.env != crate::config::app::Environment::Testing {
return Err(StartupError::RefreshDatabase(config.app.env.as_str().to_owned()));
}
if !refreshes && registrar.is_bound::<crate::db::seeders::SeedOnce>() {
return Err(StartupError::SeedOnce);
}
let seeders = std::mem::take(&mut registrar.seeders);
seeders.validate().map_err(StartupError::Seeders)?;
registrar.instance(seeders);
Ok(())
}
fn assemble(
registered: Registered,
providers: Providers,
application_providers: Providers,
booted: Vec<boot::Booted>,
config: Arc<Config>,
dotenv: DotEnv,
) -> Result<Application, StartupError> {
let Registered {
registrar,
auth_pages,
mut auth_problems,
cache,
mail,
queue,
workflow,
} = registered;
let queue_bound = registrar.is_bound::<crate::queue::QueueManager>();
let Registrar {
services: crate::container::Bindings { bindings, .. },
middleware,
mut routing,
views,
logging: log_layers,
errors,
head,
commands,
mut parts,
..
} = registrar;
let views = views.build(&config);
let encrypter = Encrypter::from_config(&config.app);
let handler = Arc::new(ErrorHandler::new(errors, &config));
let boundary = ResponseBoundary::new(Arc::clone(&handler));
let health_path = routing.health.clone();
let assets = Arc::new(Assets::new(std::mem::take(&mut routing.assets), config.app.debug));
crate::storage::web::validate(&config.filesystems).map_err(StartupError::Routes)?;
routing.routes(crate::workflow::routes);
let files = routing.collect();
let serving = table::Serving {
boundary: &|route| route.route_layer(boundary.clone()),
unmatched: |request| {
Box::pin(async move {
crate::storage::web::serve(request)
.await
.map(crate::http::Response::into_http)
})
},
};
let (router, table) = table::compile(
files,
health_path.as_deref(),
&middleware,
&serving,
&config.app.public_path(""),
&assets,
)
.map_err(StartupError::Routes)?;
auth_problems.extend(auth_pages.check_routes(&table));
let shared = Arc::new_cyclic(|shared| {
parts.insert(commands);
parts.insert(table);
parts.insert(Boot::new(Weak::clone(shared), providers, booted));
parts.insert(views);
parts.insert_shared(assets);
parts.insert(head);
parts.insert(crate::task::ticks::Ticking::default());
parts.insert(AuthProblems(auth_problems));
App {
services: Services::new(Weak::clone(shared), Arc::clone(&config), bindings),
reporter: Arc::clone(handler.reporter()),
encrypter,
config,
shutdown: Shutdown::default(),
clock: Clock::default(),
lottery_draws: crate::lottery::Draws::default(),
host: std::sync::OnceLock::new(),
parts: {
parts.insert_shared(handler);
parts
},
}
});
if let Some(factories) = cache {
let manager = CacheManager::new(
&shared.config.cache,
factories,
shared.services.container(),
crate::cache::DATABASE_STORE,
);
shared.services.insert(Arc::new(manager));
}
let mail = crate::mail::MailManager::new(&shared.config.mail, &mail, &shared.services.container());
shared.services.insert(Arc::new(mail));
if !queue_bound {
let manager = crate::queue::QueueManager::new(
&shared.config.queue,
queue,
shared.services.container(),
shared.config.app.env == crate::config::app::Environment::Testing,
);
shared.services.insert(Arc::new(manager));
}
let workflows = crate::workflow::Manager::new(&shared.config.workflow, workflow, shared.services.container());
shared.services.insert(Arc::new(workflows));
crate::task::ticks::check_dependencies(&shared).map_err(StartupError::Ticks)?;
shared
.services
.built::<Schedule>()
.expect("the application registers its schedule")
.check(&shared)
.map_err(StartupError::Schedule)?;
let router = middleware.global.apply_to_router(router);
let kernel = Kernel {
app: Arc::clone(&shared),
proxies: middleware.proxies.on_laravel_cloud(shared.config.app.laravel_cloud),
health: health_path,
};
let router = kernel::wrap(router, kernel, boundary);
Ok(Application {
router,
shared,
providers: application_providers,
log_layers: Arc::new(Mutex::new(Some(log_layers))),
dotenv,
})
}
struct AuthProblems(Vec<String>);
struct Registered {
registrar: Registrar,
auth_pages: crate::auth::Pages,
auth_problems: Vec<String>,
cache: Option<crate::cache::Factories>,
mail: crate::mail::Factories,
queue: crate::queue::Factories,
workflow: crate::workflow::Factories,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum StartupError {
#[error("the application's console commands are invalid: {0}")]
Commands(String),
#[error("the application's schedule is invalid: {0}")]
Schedule(String),
#[error("the application's ticks are invalid: {0}")]
Ticks(String),
#[error("the application's session driver is invalid: {0}")]
Session(String),
#[error("the application's feature store is invalid: {0}")]
Features(String),
#[error("the application's cache stores are invalid: {0}")]
Cache(String),
#[error("the application's search engine is invalid: {0}")]
Search(String),
#[error("the application's queue is invalid: {0}")]
Queue(String),
#[error("the application's workflows are invalid: {0}")]
Workflow(String),
#[error("the application's migrations are invalid: {0}")]
Migrations(String),
#[error("`refresh_database` drops tables, so it only runs when `APP_ENV` is `testing`, not `{0}`")]
RefreshDatabase(String),
#[error("the application's seeders are invalid: {0}")]
Seeders(String),
#[error("`seed_once` seeds the databases that `refresh_database` builds, so it needs `refresh_database` too")]
SeedOnce,
#[error("the application's broadcasting is invalid: {0}")]
Broadcast(String),
#[error("the application's mailers are invalid: {0}")]
Mail(String),
#[error("the application's SMS senders are invalid: {0}")]
Sms(String),
#[error("the application's password hashing is invalid: {0}")]
Hashing(String),
#[error(transparent)]
Env(#[from] InvalidEnv),
#[error("the application's authentication pages are invalid:\n - {}", .0.join("\n - "))]
Auth(Vec<String>),
#[error("the application's routes are invalid:\n - {}", .0.join("\n - "))]
Routes(Vec<String>),
#[error("the application's services are invalid:\n - {}", .0.join("\n - "))]
Services(Vec<String>),
#[error("the `{0}` log channel is listed twice: each destination may have one channel")]
DuplicateLogChannel(&'static str),
}
impl std::fmt::Debug for ApplicationBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ApplicationBuilder")
.field("env", &self.env)
.field("providers", &self.providers)
.finish_non_exhaustive()
}
}