use std::path::{Path, PathBuf};
use claviron_runner::RunnerOptions;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug)]
pub struct Options {
pub runner: RunnerOptions,
pub config_path: PathBuf,
pub configuration: Configuration,
}
impl Default for Options {
fn default() -> Self {
Self {
runner: RunnerOptions::default(),
config_path: "lumenize.yaml".into(),
configuration: Configuration::default(),
}
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Configuration {
pub request_mode: Option<crate::PhpRunner>,
pub php: serde_yaml::Value,
pub config_parser: PhpConfigParserOptions,
pub cache: Option<serde_yaml::Value>,
pub database: Option<serde_yaml::Value>,
pub redis: Option<serde_yaml::Value>,
pub tls: Option<serde_yaml::Value>,
pub broadcasting: Option<serde_yaml::Value>,
pub logging: Option<serde_yaml::Value>,
pub config_path: Option<PathBuf>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct PhpConfigParserOptions {
pub max_depth: usize,
}
impl Default for PhpConfigParserOptions {
fn default() -> Self {
Self { max_depth: default_config_max_depth() }
}
}
fn default_config_max_depth() -> usize {
64
}
pub(crate) type Launch = claviron_runner::launch::Launch<Configuration>;
impl From<Launch> for Options {
fn from(launch: Launch) -> Self {
Self {
runner: launch.runner,
config_path: launch
.own
.config_path
.clone()
.unwrap_or_else(|| "lumenize.yaml".into()),
configuration: launch.own,
}
}
}
impl From<Options> for Launch {
fn from(mut options: Options) -> Self {
options.configuration.config_path = Some(options.config_path);
Self { runner: options.runner, own: options.configuration }
}
}
impl Options {
pub fn from_file(path: impl AsRef<Path>) -> crate::Result<Self> {
Self::read(path.as_ref(), &RunnerOptions::default())
}
fn read(
path: &Path,
runner: &RunnerOptions,
) -> crate::Result<Self> {
let text = claviron_runner::expand_launch(
&std::fs::read_to_string(path)?,
runner,
)?;
let mut options: Self = serde_yaml::from_str::<Launch>(&text)?.into();
options.config_path = path.to_owned();
Ok(options)
}
pub(crate) fn link_instances(&self) -> crate::Result<Option<usize>> {
if self.configuration.request_mode
!= Some(crate::PhpRunner::Application)
{
return Ok(None);
}
Ok(claviron_php::embed::link_application_instances(
&self.configuration.php,
self.runner.orbit.as_ref(),
)
.map_err(|error| error.into_std())?)
}
pub fn validate(&self) -> crate::Result<()> {
self.link_instances()?;
self.runner.validate()?;
if self.config_path.as_os_str().is_empty() {
return Err("config_path must name a file".into());
}
if !self.configuration.php.is_null()
&& !self.configuration.php.is_mapping()
{
return Err("php must be a mapping".into());
}
if let Some(mode) = self.configuration.request_mode {
validate_mode(mode)?;
}
#[cfg(not(feature = "broadcast"))]
if self.configuration.broadcasting.is_some() {
return Err("broadcasting requires the broadcast feature".into());
}
self.configuration.validate_database_features()?;
self.configuration.validate_redis_feature()?;
self.configuration.validate_tls_feature()?;
if !self.runner.names_a_socket() && !self.runner.link_enabled() {
return Err("select orbit or named listeners".into());
}
Ok(())
}
pub(crate) fn system_log(
&self
) -> crate::Result<Option<claviron::logging::SystemLogConfig>> {
let Some(logging) = &self.configuration.logging else {
return Ok(None);
};
let mapping =
logging.as_mapping().ok_or("logging must be a mapping")?;
if logging.get("path").is_none() {
for key in mapping.keys() {
if !matches!(key.as_str(), Some("system_log" | "channels")) {
return Err(format!("unknown logging field {key:?}; expected system_log or channels").into());
}
}
}
let config = if logging.get("path").is_some() {
Some(logging)
} else {
logging.get("system_log").filter(|value| !value.is_null())
};
config
.map(|value| {
serde_yaml::from_value(value.clone()).map_err(Into::into)
})
.transpose()
}
#[cfg(feature = "tls")]
pub(crate) fn prepare_tls(&mut self) -> crate::Result<()> {
use claviron::http::config::{ListenerSettings, TcpSecurity};
use claviron::tls::config::{TlsConfig, TlsConfigSource};
let Some(section) = &self.configuration.tls else {
return Ok(());
};
let serves_tls = self.runner.names_a_socket()
&& self.runner.socket_listeners()?.iter().any(|listener| {
matches!(
&listener.settings,
ListenerSettings::Tcp(tcp)
if matches!(tcp.security, TcpSecurity::Tls { .. })
)
});
if !serves_tls {
return Ok(());
}
let source: TlsConfigSource = serde_yaml::from_value(section.clone())?;
let (certificate, key) = identity_files(&TlsConfig::try_from(source)?)?;
match (&self.runner.tls_cert, &self.runner.tls_key) {
(None, None) => {}
(Some(stated), Some(stated_key))
if *stated == certificate && *stated_key == key =>
{
return Ok(());
}
_ => {
return Err("declare the listener certificate once: the tls section's default identity, or tls_cert and tls_key".into());
}
}
self.runner.tls_cert = Some(certificate);
self.runner.tls_key = Some(key);
Ok(())
}
#[cfg(feature = "cli")]
pub fn from_args() -> crate::Result<Self> {
use clap::Parser;
if let Some(launch) = claviron_runner::worker_launch()? {
return Ok(Launch::into(launch));
}
#[derive(Parser)]
#[command(
about = "Serve a Laravel application through Claviron embedded PHP"
)]
struct Args {
#[arg(long, alias = "config", default_value = "lumenize.yaml")]
config_path: PathBuf,
#[command(flatten)]
runner: RunnerOptions,
}
let args = Args::parse();
let mut written = Self::read(&args.config_path, &args.runner)?;
written.runner = args.runner.over(written.runner);
written.validate()?;
Ok(written)
}
}
impl Configuration {
pub(crate) fn prepare_php(
&mut self,
root: &Path,
) -> crate::Result<Vec<String>> {
use crate::PhpRunner;
use claviron_php::embed::framework::ComposerPackages;
let packages = if self.request_mode.is_none() {
Some(ComposerPackages::read(root)?)
} else {
ComposerPackages::read(root).ok()
};
let mode = *self.request_mode.get_or_insert_with(|| {
if packages
.as_ref()
.is_some_and(|packages| packages.contains("laravel/octane"))
{
PhpRunner::Application
} else {
PhpRunner::Script
}
});
validate_mode(mode)?;
if self.php.is_null() {
self.php = serde_yaml::Value::Mapping(Default::default());
}
let php = self.php.as_mapping_mut().ok_or("php must be a mapping")?;
match mode {
PhpRunner::Application => {
if php.contains_key("script") {
return Err(
"php.script requires request_mode: script".into()
);
}
let application =
php.entry("application".into()).or_insert_with(|| {
serde_yaml::Value::Mapping(Default::default())
});
let application = application
.as_mapping_mut()
.ok_or("php.application must be a mapping")?;
if !application.contains_key("script_path") {
let entry = if root.join("application.php").try_exists()? {
PathBuf::from("application.php")
} else {
let mut args =
application.remove("args").unwrap_or_else(|| {
serde_yaml::Value::Sequence(Vec::new())
});
args.as_sequence_mut()
.ok_or("php.application.args must be a sequence")?
.insert(0, serde_yaml::to_value(root)?);
application.insert("args".into(), args);
PathBuf::from(
"vendor/claviron/laravel/runners/application.php",
)
};
application.insert(
"script_path".into(),
serde_yaml::to_value(entry)?,
);
}
}
PhpRunner::Script => {
if php.contains_key("application")
|| php.contains_key("applications")
{
return Err("php.application requires request_mode: application; script execution uses php.script and php.sapi".into());
}
}
#[allow(unreachable_patterns)]
_ => unreachable!("mode was validated"),
}
Ok(packages.map(|packages| packages.frameworks()).unwrap_or_default())
}
pub(crate) fn script_route(
&self,
state: &claviron::runtime::AppState,
) -> claviron::runtime::registry::Result<claviron_php::PhpConfig> {
use claviron::runtime::registry;
let value =
self.php.get("script").cloned().unwrap_or_else(|| {
serde_yaml::Value::Mapping(Default::default())
});
let mut route = value.as_mapping().cloned().ok_or_else(|| {
registry::Error::msg("php.script must be a mapping")
})?;
route.entry("runner".into()).or_insert("script".into());
route.entry("entry_script".into()).or_insert("index.php".into());
let route: claviron_php::PhpConfig = expand(state, &route.into())?;
if route.runner != crate::PhpRunner::Script {
return Err(registry::Error::msg(
"php.script.runner must be script",
));
}
Ok(route)
}
fn validate_database_features(&self) -> crate::Result<()> {
let Some(database) = &self.database else {
return Ok(());
};
if !cfg!(feature = "db") {
return Err("database requires a database feature (postgres, mysql or sqlite)".into());
}
let mapping =
database.as_mapping().ok_or("database must be a mapping")?;
for (backend, enabled) in [
("postgres", cfg!(feature = "postgres")),
("mysql", cfg!(feature = "mysql")),
("sqlite", cfg!(feature = "sqlite")),
] {
if mapping.contains_key(serde_yaml::Value::from(backend))
&& !enabled
{
return Err(format!(
"database.{backend} requires the {backend} feature"
)
.into());
}
}
Ok(())
}
fn validate_redis_feature(&self) -> crate::Result<()> {
if self.redis.is_some() && !cfg!(feature = "redis") {
return Err("redis requires the redis feature".into());
}
Ok(())
}
fn validate_tls_feature(&self) -> crate::Result<()> {
if self.tls.is_some() && !cfg!(feature = "tls") {
return Err("tls requires the tls feature".into());
}
Ok(())
}
#[cfg(feature = "tls")]
fn register_tls(
&self,
state: &claviron::runtime::AppState,
) -> claviron::runtime::registry::Result<()> {
use claviron::tls::config::TlsConfigSource;
let tls = self
.tls
.as_ref()
.map(|value| expand::<TlsConfigSource>(state, value))
.transpose()?
.unwrap_or_else(TlsConfigSource::absent);
claviron::tls::register_with_config(state, tls)
}
#[cfg(feature = "redis")]
fn register_redis(
&self,
state: &claviron::runtime::AppState,
) -> claviron::runtime::registry::Result<()> {
let redis = self
.redis
.as_ref()
.map(|value| expand::<claviron::cache::RedisConfig>(state, value))
.transpose()?
.unwrap_or_default();
claviron::cache::register_redis_with_config(state, redis)
}
pub(crate) fn register(
&self,
state: &claviron::runtime::AppState,
application: &str,
frameworks: Vec<String>,
icon: Option<String>,
linked: bool,
) -> claviron::runtime::registry::Result<()> {
use claviron::runtime::registry;
self.validate_database_features()
.and_then(|()| self.validate_redis_feature())
.and_then(|()| self.validate_tls_feature())
.map_err(|error| registry::Error::msg(error.to_string()))?;
#[cfg(feature = "tls")]
self.register_tls(state)?;
#[cfg(feature = "db")]
{
let database = self
.database
.as_ref()
.map(|value| expand::<claviron::db::DbFileConfig>(state, value))
.transpose()?
.unwrap_or_default();
claviron::db::register_with_config(state, database)?;
}
let mode = self.request_mode.ok_or_else(|| {
registry::Error::msg("PHP request mode was not prepared")
})?;
let mut php = self.php.clone();
if let Some(mapping) = php.as_mapping_mut() {
mapping.remove("script");
}
let yaml = serde_yaml::to_string(&php)
.map_err(|error| registry::Error::msg(error.to_string()))?;
let register_application = if linked {
claviron_php::embed::register_link_application_from_yaml
} else {
claviron_php::embed::register_application_from_yaml
};
let description = claviron::app::ApplicationDescription {
frameworks,
icon,
..claviron::app::ApplicationDescription::new("php", mode.as_str())
.runner("Lumenize")
};
match mode {
crate::PhpRunner::Application => {
register_application(state, application, &yaml, description)?
}
crate::PhpRunner::Script => {
claviron_php::embed::register_script_from_yaml(
state,
application,
&yaml,
description,
)?
}
#[allow(unreachable_patterns)]
_ => {
return Err(registry::Error::msg(
"Lumenize supports application or script request mode",
));
}
}
let root = std::env::current_dir()
.map_err(|error| registry::Error::msg(error.to_string()))?;
let parser = crate::congif::LaravelConfigParser::new(
root,
self.config_parser.max_depth,
)
.map_err(|error| registry::Error::msg(error.to_string()))?;
state.config_reader().register(parser)?;
#[cfg(feature = "redis")]
self.register_redis(state)?;
let cache = self
.cache
.as_ref()
.map(|value| expand::<claviron::cache::CacheConfig>(state, value))
.transpose()?
.unwrap_or_default();
claviron::cache::register_with_config(state, cache)?;
#[cfg(feature = "log")]
{
let mut logging = self.logging.clone().unwrap_or_else(|| {
serde_yaml::Value::Mapping(Default::default())
});
if logging.get("path").is_some() {
logging = serde_yaml::Value::Mapping(Default::default());
}
let map = logging
.as_mapping_mut()
.ok_or_else(|| registry::Error::msg("logging is a mapping"))?;
map.entry("channels".into()).or_insert_with(|| {
serde_yaml::Value::Mapping(Default::default())
});
let config = expand::<claviron::logging::pipeline::LoggingConfig>(
state, &logging,
)?;
claviron::logging::pipeline::register_with_config(state, config)?;
}
#[cfg(not(feature = "log"))]
if self
.logging
.as_ref()
.is_some_and(|value| value.get("channels").is_some())
{
return Err(registry::Error::msg(
"logging.channels requires the log feature",
));
}
#[cfg(feature = "broadcast")]
{
let mut applications = serde_yaml::Mapping::new();
if let Some(broadcasting) = &self.broadcasting {
let mut config =
broadcasting.as_mapping().cloned().ok_or_else(|| {
registry::Error::msg("broadcasting is a mapping")
})?;
config.entry("id".into()).or_insert_with(|| application.into());
applications.insert(application.into(), config.into());
}
let mut document = serde_yaml::Mapping::new();
document.insert("applications".into(), applications.into());
let config = expand::<claviron_broadcast::BroadcastConfig>(
state,
&document.into(),
)?;
claviron_broadcast::register_with_config(state, config)?;
if self.broadcasting.is_some() {
use crate::broadcast::LaravelBroadcastProvider;
use claviron::runtime::Register;
LaravelBroadcastProvider::register(state)?;
}
}
Ok(())
}
}
fn validate_mode(mode: crate::PhpRunner) -> crate::Result<()> {
if !matches!(mode, crate::PhpRunner::Application | crate::PhpRunner::Script)
{
return Err(
"Lumenize supports application or script request mode".into()
);
}
Ok(())
}
#[cfg(feature = "tls")]
fn identity_files(
config: &claviron::tls::config::TlsConfig
) -> crate::Result<(PathBuf, PathBuf)> {
use claviron::ssl::certstore::{
CertificateSource, FULLCHAIN_CERT_FILENAME, PRIVKEY_FILENAME,
};
const IN_HOSTING: &str = "tls.default selects an identity in hosting; a listener serves one from files";
let store = config.certstore();
let source = config.default_cert_entry();
match source {
CertificateSource::Name(_) | CertificateSource::Local(_) => {
let name = source.basename().ok_or(IN_HOSTING)?;
let folder = store.server_dir(name.as_str());
Ok((
folder.join(FULLCHAIN_CERT_FILENAME),
folder.join(PRIVKEY_FILENAME),
))
}
CertificateSource::Cn(_) => Err(IN_HOSTING.into()),
CertificateSource::Path(path) => {
let certificate = store.dir().join(path);
let key = certificate
.parent()
.ok_or("tls.default path names no folder")?
.join(PRIVKEY_FILENAME);
Ok((certificate, key))
}
CertificateSource::Paths(paths) => Ok((
paths.cert_path().ok_or("tls.default names no cert_path")?.clone(),
paths.key_path().ok_or("tls.default names no key_path")?.clone(),
)),
}
}
fn expand<T: serde::de::DeserializeOwned>(
state: &claviron::runtime::AppState,
value: &serde_yaml::Value,
) -> claviron::runtime::registry::Result<T> {
use claviron::runtime::registry;
let raw = serde_yaml::to_string(value)
.map_err(|error| registry::Error::msg(error.to_string()))?;
let raw = claviron::helpers::yaml::expand_env_with(&raw, |key| {
state.env_snapshot().get(key)
})
.map_err(|error| registry::Error::msg(error.to_string()))?;
serde_yaml::from_str(&raw)
.map_err(|error| registry::Error::msg(error.to_string()))
}
#[cfg(test)]
#[path = "../tests/options.rs"]
mod tests;