use std::path::PathBuf;
use std::sync::Arc;
use claviron_logging as logging;
use claviron_runtime::{
AppState, DEFAULT_FLEET_NAME, FleetCapacity, FleetIncarnation, FleetName,
FleetNodeId, LaunchBlob, RunMode, ServerName, WorkerCount,
};
#[cfg(feature = "supervisor")]
use claviron_supervisor::ProcessEntry;
use tracing::debug;
mod error;
pub use error::{Error, Result};
pub mod bootstrap;
mod instance;
#[cfg(feature = "supervisor")]
mod workers;
#[cfg(feature = "supervisor")]
pub use workers::Workers;
#[cfg(not(feature = "supervisor"))]
mod signals;
#[cfg(test)]
#[path = "../../tests/server/options.rs"]
mod tests;
use claviron_runtime::registry;
type DefinitionRegistration =
Box<dyn FnOnce(&AppState) -> registry::Result<()> + Send>;
fn chain_registration<S, R, N>(
previous: R,
next: N,
) -> impl FnOnce(&S) -> registry::Result<()>
where
R: FnOnce(&S) -> registry::Result<()>,
N: FnOnce(&S) -> registry::Result<()>,
{
move |state| {
previous(state)?;
next(state)
}
}
#[derive(Clone, Debug, Default)]
enum EnvironmentChoice {
#[default]
Local,
Named(String),
Production,
}
#[derive(Clone, Debug)]
pub struct ServerOptions {
config_dir: PathBuf,
name: Option<ServerName>,
fleet_name: FleetName,
environment: EnvironmentChoice,
#[cfg(feature = "supervisor")]
workers: Workers,
launch: LaunchBlob,
signals: claviron_sys::signal::ServerSignals,
system_log: Option<Option<logging::SystemLogConfig>>,
}
impl Default for ServerOptions {
fn default() -> Self {
Self {
config_dir: PathBuf::from("config"),
name: None,
fleet_name: FleetName::from(DEFAULT_FLEET_NAME),
environment: EnvironmentChoice::Local,
#[cfg(feature = "supervisor")]
workers: Workers::Count(0),
launch: LaunchBlob::default(),
signals: claviron_sys::signal::ServerSignals::default(),
system_log: None,
}
}
}
impl ServerOptions {
pub fn new() -> Self {
Self::default()
}
pub fn config_dir(
mut self,
config_dir: impl Into<PathBuf>,
) -> Self {
self.config_dir = config_dir.into();
self
}
pub fn name(
mut self,
name: impl Into<ServerName>,
) -> Self {
self.name = Some(name.into());
self
}
pub fn fleet_name(
mut self,
fleet_name: impl Into<FleetName>,
) -> Self {
self.fleet_name = fleet_name.into();
self
}
pub fn environment(
mut self,
environment: impl Into<String>,
) -> Self {
self.environment = EnvironmentChoice::Named(environment.into());
self
}
pub fn production(mut self) -> Self {
self.environment = EnvironmentChoice::Production;
self
}
fn resolved_environment(&self) -> registry::Result<String> {
use claviron_runtime::env::PRODUCTION;
match &self.environment {
EnvironmentChoice::Production => Ok(PRODUCTION.to_owned()),
EnvironmentChoice::Named(name)
if name.eq_ignore_ascii_case(PRODUCTION) =>
{
Err(registry::Error::msg(format!(
"the {PRODUCTION} environment is chosen explicitly (--production), never by name"
)))
}
EnvironmentChoice::Named(name) => Ok(name.clone()),
EnvironmentChoice::Local => {
Ok(claviron_runtime::env::LOCAL.to_owned())
}
}
}
pub fn launch(
mut self,
launch: impl Into<Vec<u8>>,
) -> Self {
self.launch = LaunchBlob::new(launch);
self
}
#[cfg(feature = "supervisor")]
pub fn workers(
mut self,
workers: impl Into<Workers>,
) -> Self {
self.workers = workers.into();
self
}
pub fn signals(
mut self,
signals: claviron_sys::signal::ServerSignals,
) -> Self {
self.signals = signals;
self
}
fn validate_primary(&self) -> registry::Result<()> {
claviron_runtime::env::ConfigEnvironment::validate_environment(
&self.resolved_environment()?,
)
.map_err(|error| registry::Error::msg(error.to_string()))?;
self.signals.validate().map_err(registry::Error::msg)?;
if self.config_dir.as_os_str().is_empty() {
return Err(registry::Error::msg(
"server config directory must not be empty",
));
}
Ok(())
}
pub fn build(self) -> Server {
Server::with_options(self)
}
}
pub struct Server<R = fn(&AppState) -> registry::Result<()>> {
options: ServerOptions,
register: R,
definitions: Vec<DefinitionRegistration>,
#[cfg(feature = "edge")]
edge_extensions: Vec<Arc<dyn claviron_pipeline::extension::RouteExtension>>,
}
impl Default for Server {
fn default() -> Self {
Self {
options: ServerOptions::default(),
register: |_| Ok(()),
definitions: Vec::new(),
#[cfg(feature = "edge")]
edge_extensions: Vec::new(),
}
}
}
impl Server {
pub fn new() -> Self {
Self::default()
}
pub fn with_options(options: ServerOptions) -> Self {
Server::new().options(options)
}
}
impl<R> Server<R>
where
R: FnOnce(&AppState) -> registry::Result<()>,
{
pub fn system_log(
mut self,
config: Option<logging::SystemLogConfig>,
) -> Self {
self.options.system_log = Some(config);
self
}
pub fn with_definitions<F>(
mut self,
register: F,
) -> Self
where
F: FnOnce(&AppState) -> registry::Result<()> + Send + 'static,
{
self.definitions.push(Box::new(register));
self
}
pub fn options(
mut self,
options: ServerOptions,
) -> Self {
self.options = options;
self
}
#[cfg(feature = "edge")]
pub fn with_edge_extension<E>(
mut self,
extension: E,
) -> Self
where
E: claviron_pipeline::extension::RouteExtension + 'static,
{
self.edge_extensions.push(Arc::new(extension));
self
}
pub fn config_dir(
mut self,
config_dir: impl Into<PathBuf>,
) -> Self {
self.options = self.options.config_dir(config_dir);
self
}
pub fn environment(
mut self,
environment: impl Into<String>,
) -> Self {
self.options = self.options.environment(environment);
self
}
pub fn production(mut self) -> Self {
self.options = self.options.production();
self
}
pub fn name(
mut self,
name: impl Into<ServerName>,
) -> Self {
self.options = self.options.name(name);
self
}
pub fn fleet_name(
mut self,
fleet_name: impl Into<FleetName>,
) -> Self {
self.options = self.options.fleet_name(fleet_name);
self
}
#[cfg(feature = "supervisor")]
pub fn workers(
mut self,
workers: impl Into<Workers>,
) -> Self {
self.options = self.options.workers(workers);
self
}
pub fn signals(
mut self,
signals: claviron_sys::signal::ServerSignals,
) -> Self {
self.options = self.options.signals(signals);
self
}
pub fn launch(
mut self,
launch: impl Into<Vec<u8>>,
) -> Self {
self.options = self.options.launch(launch);
self
}
pub fn register<N>(
self,
register: N,
) -> Server<impl FnOnce(&AppState) -> registry::Result<()>>
where
N: FnOnce(&AppState) -> registry::Result<()>,
{
Server {
options: self.options,
register: chain_registration(self.register, register),
definitions: self.definitions,
#[cfg(feature = "edge")]
edge_extensions: self.edge_extensions,
}
}
pub fn with_services<C>(
self
) -> Server<impl FnOnce(&AppState) -> registry::Result<()>>
where
C: claviron_runtime::Register<AppState>,
{
self.register(C::register)
}
pub fn initialize(self) -> registry::Result<AppState> {
self.initialize_as(false)
}
pub fn initialize_for_check(self) -> registry::Result<AppState> {
self.initialize_as(true)
}
fn initialize_as(
self,
check: bool,
) -> registry::Result<AppState> {
let primary_environment = self.options.resolved_environment();
#[cfg(feature = "supervisor")]
let entry = ProcessEntry::detect()
.map_err(|err| registry::Error::msg(err.to_string()))?;
#[cfg(feature = "supervisor")]
let worker_identity = match &entry {
ProcessEntry::Worker(worker) => Some(
claviron_supervisor::WorkerIdentityProvider::from_bootstrap(
worker,
)
.map_err(|err| registry::Error::msg(err.to_string()))?,
),
ProcessEntry::Primary => None,
};
#[cfg(feature = "supervisor")]
let fleet_incarnation = match &entry {
ProcessEntry::Worker(worker) => {
FleetIncarnation::new(worker.incarnation())
}
ProcessEntry::Primary => FleetIncarnation::FIRST,
};
#[cfg(feature = "supervisor")]
let launch = match &entry {
ProcessEntry::Worker(worker) => worker.launch().clone(),
ProcessEntry::Primary => self.options.launch.clone(),
};
#[cfg(not(feature = "supervisor"))]
let launch = self.options.launch.clone();
#[cfg(feature = "supervisor")]
let (
run_mode,
fleet_node_id,
worker_count,
fleet_capacity,
instance_name,
fleet_name,
config_dir,
environment,
) = match entry {
ProcessEntry::Primary => {
self.options.validate_primary()?;
let worker_count = if check {
WorkerCount::ZERO
} else {
self.options
.workers
.resolve(std::thread::available_parallelism)?
};
let fleet_capacity = FleetCapacity::BUILT;
if !fleet_capacity.admits(worker_count) {
return Err(registry::Error::msg(format!(
"worker count {} exceeds fleet worker capacity {}",
worker_count.raw(),
fleet_capacity.worker_capacity()
)));
}
let run_mode = if worker_count.is_zero() {
RunMode::Standalone
} else {
RunMode::Master
};
(
run_mode,
FleetNodeId::ZERO,
worker_count,
fleet_capacity,
self.options.name.map(Arc::from),
Arc::from(self.options.fleet_name),
self.options.config_dir,
primary_environment?,
)
}
ProcessEntry::Worker(ref worker) => (
worker.run_mode(),
worker.fleet_node_id(),
worker.worker_count(),
worker.fleet_capacity(),
Some(Arc::from(worker.instance_name())),
Arc::from(worker.fleet_name()),
worker.config_dir().to_path_buf(),
worker.environment().to_owned(),
),
};
#[cfg(not(feature = "supervisor"))]
let fleet_incarnation = FleetIncarnation::FIRST;
#[cfg(not(feature = "supervisor"))]
let (
run_mode,
fleet_node_id,
worker_count,
fleet_capacity,
instance_name,
fleet_name,
config_dir,
environment,
) = {
self.options.validate_primary()?;
(
RunMode::Standalone,
FleetNodeId::ZERO,
WorkerCount::ZERO,
FleetCapacity::BUILT,
self.options.name.map(Arc::from),
Arc::from(self.options.fleet_name),
self.options.config_dir,
primary_environment?,
)
};
let hostname = claviron_sys::short_hostname();
let under_systemd = logging::is_running_under_systemd();
let config_environment =
claviron_runtime::env::ConfigEnvironment::load(
&hostname,
&environment,
std::path::Path::new(".env"),
)
.map_err(|error| registry::Error::msg(error.to_string()))?;
let system_log = |config_dir: &std::path::Path| {
if let Some(config) = &self.options.system_log {
let Some(config) = config else { return Ok(None) };
let config = config
.resolve(|key| config_environment.snapshot().get(key))?;
return if check {
config.validate().map(|()| None)
} else {
logging::SystemLog::from_configuration(config, run_mode)
.map(Some)
};
}
if check {
logging::SystemLog::check_config_dir(config_dir, |key| {
config_environment.snapshot().get(key)
})
.map(|()| None)
} else {
logging::SystemLog::from_config_dir_for_startup(
config_dir,
|key| config_environment.snapshot().get(key),
run_mode,
)
}
};
let rust_log = config_environment.snapshot().get("RUST_LOG");
if under_systemd {
logging::journald_logger_with_filter(
run_mode,
system_log(&config_dir)?,
rust_log.as_deref(),
)?;
} else {
logging::console_logger_with_filter(
run_mode,
system_log(&config_dir)?,
rust_log.as_deref(),
)?;
}
let state = AppState::initialize_with_environment_in_fleet(
run_mode,
fleet_node_id,
worker_count,
fleet_capacity,
instance_name,
fleet_name,
hostname,
config_dir,
config_environment,
);
#[cfg(feature = "supervisor")]
if let ProcessEntry::Worker(worker) = &entry {
unsafe { worker.install_resources(&state) }
.map_err(|error| registry::Error::msg(error.to_string()))?;
}
#[cfg(feature = "supervisor")]
if let Some(identity) = worker_identity {
state.registry_ref().insert(Arc::new(identity))?;
}
if check {
state
.registry_ref()
.insert(Arc::new(claviron_runtime::ConfigCheck))?;
}
state.registry_ref().insert(Arc::new(fleet_incarnation))?;
state.registry_ref().insert(Arc::new(launch))?;
debug!(
role = %run_mode.as_process_label(),
pid = state.pid(),
instance = state.name(),
fleet = state.fleet_name(),
config_dir = %state.config_dir().display(),
environment = state.environment(),
"🆔 Claviron process starting; registering providers"
);
for register in self.definitions {
register(&state)?;
}
bootstrap::register(&state)?;
#[cfg(feature = "edge")]
{
let registry = state
.registry_ref()
.resolve::<claviron_edge::HostAppRegistry>()
.ok_or_else(|| {
registry::Error::msg("edge registry is not registered")
})?;
for extension in self.edge_extensions {
registry.register_route_extension(extension)?;
}
}
(self.register)(&state)?;
Ok(state)
}
pub async fn check_config(self) -> crate::Result<()> {
let state = self.initialize_for_check().map_err(Error::from)?;
let registry = state.registry_ref();
let mut runtime = claviron_runtime::Runtime::default();
registry.insert(runtime.manager()).map_err(Error::from)?;
runtime = bootstrap::with_http_services(runtime);
claviron_orbit::service::register(&state).map_err(Error::from)?;
runtime.configure(&state).await.map_err(Error::from)?;
registry.boot_all(&state).await.map_err(Error::from)?;
let validation = registry.validate_all(&state).map_err(Error::from)?;
for failure in validation.failures() {
tracing::error!(
component = failure.component(),
error = %failure.error(),
"provider '{}' validation failed: {}",
failure.component(),
failure.error()
);
}
if validation.is_valid() {
tracing::info!("configuration is valid");
Ok(())
} else {
Err(registry::Error::msg(format!(
"{} provider validation(s) failed",
validation.failed_count()
))
.into())
}
}
pub async fn serve(self) -> crate::Result<()> {
let signals = self.options.signals;
let state = self.initialize().map_err(Error::from)?;
bootstrap::start_services(state, signals).await?;
Ok(())
}
}