use std::sync::Arc;
use claviron::runtime::{AppState, Register, registry};
use claviron_runner::{Composition, Owner};
use crate::Options;
use crate::application::{PhpOwner, PhpService};
use crate::options::Launch;
const PHP_RUNTIME: &str = "php";
type Registration = Box<dyn FnOnce(&AppState) -> registry::Result<()> + Send>;
#[derive(Default)]
pub struct Runner {
options: Options,
request_mode: Option<crate::PhpRunner>,
registrations: Vec<Registration>,
#[cfg(feature = "axum")]
interceptor: Option<Registration>,
}
impl Runner {
pub fn new() -> Self {
Self::default()
}
pub fn with_options(
mut self,
options: Options,
) -> Self {
self.options = options;
self
}
pub fn with_request_mode(
mut self,
mode: crate::PhpRunner,
) -> Self {
self.request_mode = Some(mode);
self
}
pub fn with_config_path(
mut self,
path: impl AsRef<std::path::Path>,
) -> crate::Result<Self> {
self.options = Options::from_file(path)?;
Ok(self)
}
pub fn with_fleet_name(
mut self,
name: impl Into<crate::FleetName>,
) -> Self {
self.options.runner.fleet_name = Some(name.into().to_string());
self
}
pub fn with_services<C: Register<AppState> + 'static>(self) -> Self {
self.with_bootstrap(C::register)
}
pub fn with_bootstrap<F>(
mut self,
configure: F,
) -> Self
where
F: FnOnce(&AppState) -> registry::Result<()> + Send + 'static,
{
self.registrations.push(Box::new(configure));
self
}
#[cfg(feature = "axum")]
pub fn with_interceptor<F>(
mut self,
router: F,
) -> Self
where
F: FnOnce(AppState) -> claviron::axum::Router + Send + 'static,
{
self.interceptor = Some(Box::new(move |state| {
claviron_runner::register_router(state, router)
}));
self
}
pub async fn run(mut self) -> crate::Result<()> {
let registrations = self.registrations;
#[cfg(feature = "axum")]
let interceptor = self.interceptor;
if let Some(mode) = self.request_mode {
self.options.configuration.request_mode = Some(mode);
}
let root = std::env::current_dir()?;
let detected_framework =
self.options.configuration.prepare_php(&root)?;
if self.options.runner.frameworks.is_none() {
self.options.runner.frameworks = Some(detected_framework);
}
self.options.runner.icon.get_or_insert_with(|| "laravel".into());
self.options.validate()?;
let name =
self.options.runner.name.clone().ok_or("name is required")?;
#[cfg(feature = "watch")]
if self.options.runner.watch
&& self.options.runner.workers.unwrap_or(0) > 0
{
return Err(
"watch restarts the PHP application in its process: run it standalone".into(),
);
}
let system_log = self.options.system_log()?;
let link_capacity = self.options.link_instances()?;
let config_path = self.options.config_path.clone();
let launch = Launch::from(self.options);
let definition_name = name.clone();
let owner_name = name.clone();
let application = name.clone();
Composition::new(launch, name, PHP_RUNTIME, move |state, launch| {
let php = PhpService::new();
let script =
if launch.own.request_mode == Some(crate::PhpRunner::Script) {
Some(launch.own.script_route(state)?)
} else {
None
};
let execution = if script.is_some() {
state
.registry_ref()
.resolve::<claviron_php::embed::PhpScriptService>()
.map_or(claviron::ExecutorSpec::Inherit, |service| {
service.execution()
})
} else {
claviron::ExecutorSpec::Dedicated(
claviron::ExecutorKind::CurrentThread,
)
};
state.registry_ref().register(Arc::new(PhpOwner::new(
owner_name,
php.clone(),
script,
)))?;
let owner = Owner::new(execution, php);
#[cfg(feature = "broadcast")]
let owner = claviron_broadcast::runner::in_front(state, owner)?;
Ok(owner)
})
.default_in_flight(
link_capacity.map(|limit| (limit, "php.application.instances")),
)
.config_path(&config_path)
.system_log(system_log)
.definitions(move |state, launch| {
launch.own.register(
state,
&definition_name,
launch.runner.frameworks.clone().unwrap_or_default(),
launch.runner.icon.clone(),
launch.runner.link_enabled(),
)?;
claviron_php::register(state)
})
.configure(move |state, _| {
for register in registrations {
register(state)?;
}
#[cfg(feature = "axum")]
if let Some(interceptor) = interceptor {
interceptor(state)?;
}
Ok(())
})
.settled(move |state, launch| {
#[cfg(feature = "watch")]
if launch.runner.watch {
let root = std::env::current_dir()
.map_err(|error| registry::Error::msg(error.to_string()))?;
let watcher = crate::watch::watcher(
root,
launch.runner.watch_paths.clone(),
application,
)
.map_err(registry::Error::msg)?;
state.registry_ref().register(Arc::new(watcher))?;
}
#[cfg(not(feature = "watch"))]
let _ = (state, launch, application);
Ok(())
})
.serve()
.await?;
Ok(())
}
}