#![doc = include_str!("../README.md")]
#![doc = include_str!("../docs/cli-reference.md")]
#![warn(clippy::all, clippy::pedantic)]
#![allow(clippy::missing_errors_doc)]
mod cmds;
mod permission;
mod units;
use clap::{Args, Parser, Subcommand};
use clap_verbosity_flag::{Verbosity, WarnLevel};
use clio::ClioPath;
use saferlmdb::{EnvBuilder, Environment};
use std::env::home_dir;
use std::path::Path;
use std::sync::Arc;
use tracing::{Level, instrument};
use tracing_subscriber::fmt::format::FmtSpan;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use crate::cmds::accounts::HostDomainAccount;
use crate::cmds::ssg::Ssg;
use crate::cmds::utils::Utils;
pub use cmds::app::assets::Assets;
pub use cmds::app::database::Database;
pub use cmds::{accounts::Accounts, app::App, host::Host};
use ordinary_config::COMMIT_HASH;
use ordinary_config::{
APP_CONFIG_FILENAME, FfiVersion, HOST_CONFIG_FILENAME, OrdinaryAppConfig, OrdinaryHostConfig,
};
use ordinary_host::client::OrdinaryHostClient;
pub use permission::Permission;
#[cfg(target_os = "macos")]
pub static USER_AGENT: &str = concat!(
env!("CARGO_PKG_NAME"),
"/",
env!("CARGO_PKG_VERSION"),
" (macOS)"
);
#[cfg(target_os = "linux")]
pub static USER_AGENT: &str = concat!(
env!("CARGO_PKG_NAME"),
"/",
env!("CARGO_PKG_VERSION"),
" (Linux)"
);
#[cfg(target_os = "freebsd")]
pub static USER_AGENT: &str = concat!(
env!("CARGO_PKG_NAME"),
"/",
env!("CARGO_PKG_VERSION"),
" (FreeBSD)"
);
#[cfg(all(
unix,
not(target_os = "macos"),
not(target_os = "linux"),
not(target_os = "freebsd")
))]
pub static USER_AGENT: &str = concat!(
env!("CARGO_PKG_NAME"),
"/",
env!("CARGO_PKG_VERSION"),
" (Unix)"
);
#[cfg(all(
not(unix),
not(target_os = "macos"),
not(target_os = "linux"),
not(target_os = "freebsd")
))]
pub static USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));
pub(crate) fn add_http(domain: &str, insecure: bool) -> String {
if insecure {
format!("http://{domain}")
} else {
format!("https://{domain}")
}
}
#[derive(Debug, Args, Clone)]
pub struct HostCallFlags {
#[arg(long, global = true)]
pub host_domain: Option<String>,
#[arg(long, global = true, default_value_t = false)]
pub insecure: bool,
#[arg(long, global = true, default_value_t = false)]
pub danger_accept_invalid_certs: bool,
}
impl HostCallFlags {
fn client<'a>(
&'a self,
HostDomainAccount(host, _domain, account): &'a HostDomainAccount,
env: &Arc<Environment>,
) -> anyhow::Result<OrdinaryHostClient<'a>> {
let client = OrdinaryHostClient::new(
host,
account,
self.host_domain.as_deref(),
self.danger_accept_invalid_certs,
USER_AGENT,
false,
OrdinaryHostClient::secrets_store("cli", env)?,
)?;
Ok(client)
}
}
#[derive(Parser, Debug)]
#[command(version = format!("{} ({COMMIT_HASH})", env!("CARGO_PKG_VERSION")), about, long_about = None)]
#[command(propagate_version = true, arg_required_else_help = true)]
pub struct Cli {
#[command(subcommand)]
pub commands: Commands,
#[command(flatten)]
pub verbosity: Verbosity<WarnLevel>,
#[arg(long, global = true, default_value_t = false)]
pub pretty: bool,
}
#[derive(Subcommand, Debug)]
pub enum Commands {
App {
#[command(subcommand)]
app: App,
},
Ssg {
#[arg(short, long, value_parser = clap::value_parser!(ClioPath).exists().is_dir(), default_value = ".")]
project: ClioPath,
#[command(subcommand)]
ssg: Ssg,
},
Host {
#[command(subcommand)]
host: Host,
},
#[clap(visible_aliases(["dr"]))]
Doctor {
#[arg(short, long, value_delimiter = ',', num_args = 1..)]
fix: Option<Vec<ordinary_doctor::Fix>>,
},
Utils {
#[command(subcommand)]
utils: Utils,
},
}
pub fn setup(cli: &Cli) -> anyhow::Result<()> {
let pretty_layer = if cli.pretty {
Some(
tracing_subscriber::fmt::layer()
.pretty()
.with_span_events(FmtSpan::CLOSE)
.with_writer(std::io::stderr),
)
} else {
None
};
let ugly_layer = if cli.pretty {
None
} else {
Some(
tracing_subscriber::fmt::layer()
.with_span_events(FmtSpan::CLOSE)
.with_target(false)
.with_writer(std::io::stderr),
)
};
let log_level_str = cli
.verbosity
.tracing_level()
.unwrap_or(Level::INFO)
.as_str()
.to_ascii_lowercase();
let directives = [
("ordinaryd", &log_level_str), ("ordinary_modify", &log_level_str), ("ordinary_types", &log_level_str), ("ordinary_build", &log_level_str), ("ordinary_build_utils", &log_level_str), ("ordinary_test_utils", &log_level_str), ("ordinary_builtins", &log_level_str), ("ordinary_assets", &log_level_str), ("ordinary_doctor", &log_level_str), ("ordinary_server_utils", &log_level_str), ("ordinary_auth", &log_level_str), ("ordinary_host", &log_level_str), ("ordinary_app", &log_level_str), ("ordinary_function", &log_level_str), ("ordinary_extension", &log_level_str), ("ordinary_storage", &log_level_str), ("ordinary_monitor", &log_level_str), ("ordinary_config", &log_level_str), ("tower_http", &log_level_str), ];
let mut directives_string = format!("ordinary={log_level_str}");
for (lib, lvl) in directives {
directives_string = format!("{directives_string},{lib}={lvl}");
}
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| directives_string.into()),
)
.with(pretty_layer)
.with(ugly_layer)
.init();
std::panic::set_hook(Box::new(|info| {
if let Some(msg) = info.payload_as_str()
&& let Some(loc) = info.location()
{
tracing::error!(%loc, msg, "panic");
} else if let Some(loc) = info.location() {
tracing::error!(%loc, "panic");
}
}));
Ok(())
}
#[expect(clippy::missing_panics_doc)]
#[instrument(name = "ordinary", skip_all, err)]
pub async fn run(cli: &Cli) -> anyhow::Result<()> {
let storage_size = 16384 * 64 * 10;
let ps = page_size::get() as u64;
let remainder = storage_size % ps;
let mapsize = (storage_size - remainder) + ps;
tracing::debug!(mapsize = %bytesize::ByteSize(mapsize).display().si_short());
let cli_path = home_dir()
.expect("failed to get home dir")
.join(".ordinary")
.join("cli")
.join("data");
if !cli_path.exists() {
fs_err::create_dir_all(&cli_path)?;
}
let env = Arc::new(unsafe {
let mut env_builder = EnvBuilder::new()?;
env_builder.set_maxreaders(126)?;
env_builder.set_mapsize(usize::try_from(mapsize)?)?;
env_builder.set_maxdbs(14)?;
env_builder.open(
cli_path.to_str().expect("store_path not a str"),
&saferlmdb::open::Flags::NORDAHEAD,
0o600,
)?
});
match &cli.commands {
Commands::Ssg { ssg, project } => {
let project = project.to_str().expect("failed to get string from project");
ssg.handle(project)?;
}
Commands::App { app } => {
app.handle(&env).await?;
}
Commands::Host { host } => {
host.handle(&env).await?;
}
Commands::Doctor { fix } => {
ordinary_doctor::doctor(&fix.clone().unwrap_or(vec![]))?;
}
Commands::Utils { utils } => {
utils.handle()?;
}
}
Ok(())
}
pub fn deploy_host_local(
data_dir: impl AsRef<Path>,
project: impl AsRef<Path>,
config: &OrdinaryHostConfig,
) -> anyhow::Result<()> {
let host_dir = data_dir.as_ref().join("hosts").join(&config.domain);
if !host_dir.exists() {
std::fs::create_dir_all(&host_dir)?;
}
let config_json = serde_json::to_string_pretty(&config)?;
fs_err::write(host_dir.join(HOST_CONFIG_FILENAME), config_json.as_bytes())?;
for extension_config in &config.extensions {
let extension_bytes = match extension_config.ffi_validated().version {
FfiVersion::V1 => {
if let Some(bin) = &extension_config.bin {
if let Some(reference) = &extension_config.r#ref
&& let Some(ref_dir) = project.as_ref().join(reference).parent()
{
std::fs::read(ref_dir.join(bin))?
} else {
std::fs::read(bin)?
}
} else {
continue;
}
}
};
let registry_dir = host_dir.join("extensions").join(
extension_config
.registry
.clone()
.unwrap_or(config.domain.clone()),
);
if !registry_dir.exists() {
std::fs::create_dir_all(®istry_dir)?;
}
let mut extension_path = registry_dir.join(extension_config.name_validated());
extension_path.add_extension("wasm");
std::fs::write(extension_path, extension_bytes)?;
}
Ok(())
}
pub fn deploy_app_local(
host: Option<&str>,
data_dir: impl AsRef<Path>,
project: impl AsRef<Path>,
config: &OrdinaryAppConfig,
) -> anyhow::Result<()> {
let app_dir = data_dir.as_ref().join("apps").join(&config.domain(host)?);
if !app_dir.exists() {
std::fs::create_dir_all(&app_dir)?;
}
let config_json = serde_json::to_string_pretty(&config)?;
fs_err::write(app_dir.join(APP_CONFIG_FILENAME), config_json.as_bytes())?;
if let Some(function_configs) = &config.functions {
for function_config in function_configs {
let extension_bytes = match function_config.ffi_validated().version {
FfiVersion::V1 => {
if let Some(bin) = &function_config.bin {
if let Some(reference) = &function_config.r#ref
&& let Some(ref_dir) = project.as_ref().join(reference).parent()
{
std::fs::read(ref_dir.join(bin))?
} else {
std::fs::read(bin)?
}
} else {
continue;
}
}
};
let functions_dir = app_dir.join("functions");
if !functions_dir.exists() {
std::fs::create_dir_all(&functions_dir)?;
}
let mut extension_path = functions_dir.join(function_config.name_validated());
extension_path.add_extension("wasm");
std::fs::write(extension_path, extension_bytes)?;
}
}
Ok(())
}