Skip to main content

ordinary/
lib.rs

1#![doc = include_str!("../README.md")]
2#![doc = include_str!("../docs/cli-reference.md")]
3#![warn(clippy::all, clippy::pedantic)]
4#![allow(clippy::missing_errors_doc)]
5
6// Copyright (C) 2026 The Ordinary Authors.
7//
8// SPDX-License-Identifier: BSD-3-Clause
9
10mod cmds;
11mod permission;
12mod units;
13
14use clap::{Args, Parser, Subcommand};
15use clap_verbosity_flag::{Verbosity, WarnLevel};
16use clio::ClioPath;
17use saferlmdb::{EnvBuilder, Environment};
18use std::env::home_dir;
19use std::path::Path;
20use std::sync::Arc;
21use tracing::{Level, instrument};
22use tracing_subscriber::fmt::format::FmtSpan;
23use tracing_subscriber::layer::SubscriberExt;
24use tracing_subscriber::util::SubscriberInitExt;
25
26use crate::cmds::accounts::HostDomainAccount;
27use crate::cmds::ssg::Ssg;
28use crate::cmds::utils::Utils;
29pub use cmds::app::assets::Assets;
30pub use cmds::app::database::Database;
31pub use cmds::{accounts::Accounts, app::App, host::Host};
32use ordinary_config::COMMIT_HASH;
33use ordinary_config::{
34    APP_CONFIG_FILENAME, FfiVersion, HOST_CONFIG_FILENAME, OrdinaryAppConfig, OrdinaryHostConfig,
35};
36use ordinary_host::client::OrdinaryHostClient;
37pub use permission::Permission;
38
39#[cfg(target_os = "macos")]
40pub static USER_AGENT: &str = concat!(
41    env!("CARGO_PKG_NAME"),
42    "/",
43    env!("CARGO_PKG_VERSION"),
44    " (macOS)"
45);
46#[cfg(target_os = "linux")]
47pub static USER_AGENT: &str = concat!(
48    env!("CARGO_PKG_NAME"),
49    "/",
50    env!("CARGO_PKG_VERSION"),
51    " (Linux)"
52);
53#[cfg(target_os = "freebsd")]
54pub static USER_AGENT: &str = concat!(
55    env!("CARGO_PKG_NAME"),
56    "/",
57    env!("CARGO_PKG_VERSION"),
58    " (FreeBSD)"
59);
60#[cfg(all(
61    unix,
62    not(target_os = "macos"),
63    not(target_os = "linux"),
64    not(target_os = "freebsd")
65))]
66pub static USER_AGENT: &str = concat!(
67    env!("CARGO_PKG_NAME"),
68    "/",
69    env!("CARGO_PKG_VERSION"),
70    " (Unix)"
71);
72#[cfg(all(
73    not(unix),
74    not(target_os = "macos"),
75    not(target_os = "linux"),
76    not(target_os = "freebsd")
77))]
78pub static USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));
79
80pub(crate) fn add_http(domain: &str, insecure: bool) -> String {
81    if insecure {
82        format!("http://{domain}")
83    } else {
84        format!("https://{domain}")
85    }
86}
87
88#[derive(Debug, Args, Clone)]
89pub struct HostCallFlags {
90    /// should only be necessary with localhost or when addressing by IP
91    #[arg(long, global = true)]
92    pub host_domain: Option<String>,
93
94    /// use HTTP instead of HTTPS
95    #[arg(long, global = true, default_value_t = false)]
96    pub insecure: bool,
97
98    /// DANGER: only use when working with self-signed localhost certs
99    #[arg(long, global = true, default_value_t = false)]
100    pub danger_accept_invalid_certs: bool,
101}
102
103impl HostCallFlags {
104    fn client<'a>(
105        &'a self,
106        HostDomainAccount(host, _domain, account): &'a HostDomainAccount,
107        env: &Arc<Environment>,
108    ) -> anyhow::Result<OrdinaryHostClient<'a>> {
109        let client = OrdinaryHostClient::new(
110            host,
111            account,
112            self.host_domain.as_deref(),
113            self.danger_accept_invalid_certs,
114            USER_AGENT,
115            false,
116            OrdinaryHostClient::secrets_store("cli", env)?,
117        )?;
118
119        Ok(client)
120    }
121}
122
123#[derive(Parser, Debug)]
124#[command(version = format!("{} ({COMMIT_HASH})", env!("CARGO_PKG_VERSION")), about, long_about = None)]
125#[command(propagate_version = true, arg_required_else_help = true)]
126pub struct Cli {
127    #[command(subcommand)]
128    pub commands: Commands,
129
130    #[command(flatten)]
131    pub verbosity: Verbosity<WarnLevel>,
132
133    /// whether to pretty print events to stdio
134    #[arg(long, global = true, default_value_t = false)]
135    pub pretty: bool,
136}
137
138#[derive(Subcommand, Debug)]
139pub enum Commands {
140    /// manage applications running on `ordinaryd`
141    App {
142        #[command(subcommand)]
143        app: App,
144    },
145    /// manage static site configuration
146    Ssg {
147        /// project path
148        #[arg(short, long, value_parser = clap::value_parser!(ClioPath).exists().is_dir(), default_value = ".")]
149        project: ClioPath,
150
151        #[command(subcommand)]
152        ssg: Ssg,
153    },
154    /// manage an `ordinaryd` instance
155    Host {
156        #[command(subcommand)]
157        host: Host,
158    },
159    /// ensure that all the correct system components are installed
160    #[clap(visible_aliases(["dr"]))]
161    Doctor {
162        /// auto fix installs
163        #[arg(short, long, value_delimiter = ',', num_args = 1..)]
164        fix: Option<Vec<ordinary_doctor::Fix>>,
165    },
166    /// utility functions for aiding project development
167    Utils {
168        #[command(subcommand)]
169        utils: Utils,
170    },
171}
172
173pub fn setup(cli: &Cli) -> anyhow::Result<()> {
174    let pretty_layer = if cli.pretty {
175        Some(
176            tracing_subscriber::fmt::layer()
177                .pretty()
178                .with_span_events(FmtSpan::CLOSE)
179                .with_writer(std::io::stderr),
180        )
181    } else {
182        None
183    };
184
185    let ugly_layer = if cli.pretty {
186        None
187    } else {
188        Some(
189            tracing_subscriber::fmt::layer()
190                .with_span_events(FmtSpan::CLOSE)
191                .with_target(false)
192                .with_writer(std::io::stderr),
193        )
194    };
195
196    let log_level_str = cli
197        .verbosity
198        .tracing_level()
199        .unwrap_or(Level::INFO)
200        .as_str()
201        .to_ascii_lowercase();
202
203    let directives = [
204        ("ordinaryd", &log_level_str),             // daemon
205        ("ordinary_modify", &log_level_str),       // modify
206        ("ordinary_types", &log_level_str),        // types
207        ("ordinary_build", &log_level_str),        // build
208        ("ordinary_build_utils", &log_level_str),  // build_utils
209        ("ordinary_test_utils", &log_level_str),   // test_utils
210        ("ordinary_builtins", &log_level_str),     // builtins
211        ("ordinary_assets", &log_level_str),       // assets
212        ("ordinary_doctor", &log_level_str),       // doctor
213        ("ordinary_server_utils", &log_level_str), // utils
214        ("ordinary_auth", &log_level_str),         // auth
215        ("ordinary_host", &log_level_str),         // api
216        ("ordinary_app", &log_level_str),          // app
217        ("ordinary_function", &log_level_str),     // functions
218        ("ordinary_extension", &log_level_str),    // extension
219        ("ordinary_storage", &log_level_str),      // storage
220        ("ordinary_monitor", &log_level_str),      // monitor
221        ("ordinary_config", &log_level_str),       // config
222        ("tower_http", &log_level_str),            // http
223    ];
224
225    let mut directives_string = format!("ordinary={log_level_str}");
226
227    for (lib, lvl) in directives {
228        directives_string = format!("{directives_string},{lib}={lvl}");
229    }
230
231    tracing_subscriber::registry()
232        .with(
233            tracing_subscriber::EnvFilter::try_from_default_env()
234                .unwrap_or_else(|_| directives_string.into()),
235        )
236        .with(pretty_layer)
237        .with(ugly_layer)
238        .init();
239
240    std::panic::set_hook(Box::new(|info| {
241        if let Some(msg) = info.payload_as_str()
242            && let Some(loc) = info.location()
243        {
244            tracing::error!(%loc, msg, "panic");
245        } else if let Some(loc) = info.location() {
246            tracing::error!(%loc, "panic");
247        }
248    }));
249
250    Ok(())
251}
252
253#[expect(clippy::missing_panics_doc)]
254#[instrument(name = "ordinary", skip_all, err)]
255pub async fn run(cli: &Cli) -> anyhow::Result<()> {
256    let storage_size = 16384 * 64 * 10;
257    let ps = page_size::get() as u64;
258
259    let remainder = storage_size % ps;
260    let mapsize = (storage_size - remainder) + ps;
261
262    tracing::debug!(mapsize = %bytesize::ByteSize(mapsize).display().si_short());
263
264    let cli_path = home_dir()
265        .expect("failed to get home dir")
266        .join(".ordinary")
267        .join("cli")
268        .join("data");
269
270    if !cli_path.exists() {
271        fs_err::create_dir_all(&cli_path)?;
272    }
273
274    let env = Arc::new(unsafe {
275        let mut env_builder = EnvBuilder::new()?;
276        env_builder.set_maxreaders(126)?;
277        env_builder.set_mapsize(usize::try_from(mapsize)?)?;
278        env_builder.set_maxdbs(14)?;
279        env_builder.open(
280            cli_path.to_str().expect("store_path not a str"),
281            // todo: flags should be configurable
282            // &(saferlmdb::open::Flags::NORDAHEAD
283            //                | saferlmdb::open::Flags::WRITEMAP
284            //                | saferlmdb::open::Flags::MAPASYNC),
285            &saferlmdb::open::Flags::NORDAHEAD,
286            0o600,
287        )?
288    });
289
290    match &cli.commands {
291        Commands::Ssg { ssg, project } => {
292            let project = project.to_str().expect("failed to get string from project");
293            ssg.handle(project)?;
294        }
295        Commands::App { app } => {
296            app.handle(&env).await?;
297        }
298        Commands::Host { host } => {
299            host.handle(&env).await?;
300        }
301        Commands::Doctor { fix } => {
302            ordinary_doctor::doctor(&fix.clone().unwrap_or(vec![]))?;
303        }
304        Commands::Utils { utils } => {
305            utils.handle()?;
306        }
307    }
308
309    Ok(())
310}
311
312pub fn deploy_host_local(
313    data_dir: impl AsRef<Path>,
314    project: impl AsRef<Path>,
315    config: &OrdinaryHostConfig,
316) -> anyhow::Result<()> {
317    let host_dir = data_dir.as_ref().join("hosts").join(&config.domain);
318
319    if !host_dir.exists() {
320        std::fs::create_dir_all(&host_dir)?;
321    }
322
323    let config_json = serde_json::to_string_pretty(&config)?;
324    fs_err::write(host_dir.join(HOST_CONFIG_FILENAME), config_json.as_bytes())?;
325
326    for extension_config in &config.extensions {
327        let extension_bytes = match extension_config.ffi_validated().version {
328            FfiVersion::V1 => {
329                if let Some(bin) = &extension_config.bin {
330                    if let Some(reference) = &extension_config.r#ref
331                        && let Some(ref_dir) = project.as_ref().join(reference).parent()
332                    {
333                        std::fs::read(ref_dir.join(bin))?
334                    } else {
335                        std::fs::read(bin)?
336                    }
337                } else {
338                    continue;
339                }
340            }
341        };
342
343        let registry_dir = host_dir.join("extensions").join(
344            extension_config
345                .registry
346                .clone()
347                .unwrap_or(config.domain.clone()),
348        );
349
350        if !registry_dir.exists() {
351            std::fs::create_dir_all(&registry_dir)?;
352        }
353
354        let mut extension_path = registry_dir.join(extension_config.name_validated());
355
356        extension_path.add_extension("wasm");
357
358        std::fs::write(extension_path, extension_bytes)?;
359    }
360
361    Ok(())
362}
363
364pub fn deploy_app_local(
365    host: Option<&str>,
366    data_dir: impl AsRef<Path>,
367    project: impl AsRef<Path>,
368    config: &OrdinaryAppConfig,
369) -> anyhow::Result<()> {
370    let app_dir = data_dir.as_ref().join("apps").join(&config.domain(host)?);
371
372    if !app_dir.exists() {
373        std::fs::create_dir_all(&app_dir)?;
374    }
375
376    let config_json = serde_json::to_string_pretty(&config)?;
377    fs_err::write(app_dir.join(APP_CONFIG_FILENAME), config_json.as_bytes())?;
378
379    if let Some(function_configs) = &config.functions {
380        for function_config in function_configs {
381            let extension_bytes = match function_config.ffi_validated().version {
382                FfiVersion::V1 => {
383                    if let Some(bin) = &function_config.bin {
384                        if let Some(reference) = &function_config.r#ref
385                            && let Some(ref_dir) = project.as_ref().join(reference).parent()
386                        {
387                            std::fs::read(ref_dir.join(bin))?
388                        } else {
389                            std::fs::read(bin)?
390                        }
391                    } else {
392                        continue;
393                    }
394                }
395            };
396
397            let functions_dir = app_dir.join("functions");
398
399            if !functions_dir.exists() {
400                std::fs::create_dir_all(&functions_dir)?;
401            }
402
403            let mut extension_path = functions_dir.join(function_config.name_validated());
404
405            extension_path.add_extension("wasm");
406
407            std::fs::write(extension_path, extension_bytes)?;
408        }
409    }
410
411    Ok(())
412}