diff --git a/Cargo.lock b/Cargo.lock index 58db82c7..df93b3fc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -729,6 +729,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + [[package]] name = "libc" version = "0.2.190" @@ -753,6 +759,15 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + [[package]] name = "matchit" version = "0.8.4" @@ -782,6 +797,15 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -851,6 +875,7 @@ dependencies = [ "tokio", "toml", "tracing", + "tracing-subscriber", "utoipa", "utoipa-axum", "zstd", @@ -1118,6 +1143,15 @@ dependencies = [ "digest", ] +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + [[package]] name = "shlex" version = "2.0.1" @@ -1274,6 +1308,15 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + [[package]] name = "tinystr" version = "0.8.4" @@ -1423,6 +1466,36 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", ] [[package]] @@ -1504,6 +1577,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + [[package]] name = "want" version = "0.3.2" diff --git a/Cargo.toml b/Cargo.toml index c50c4e2f..a471af07 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -45,6 +45,7 @@ thiserror = "2.0.21" tokio = { version = "1.53.3", features = ["macros", "net", "rt-multi-thread", "signal"] } toml = "1.1.8" tracing = "0.1.44" +tracing-subscriber = { version = "0.3.23", features = ["env-filter", "fmt"] } utoipa = { version = "6.0.0", features = ["axum_extras"] } utoipa-axum = "0.3.0" zstd = "0.14.3" diff --git a/README.md b/README.md index 9cf3cfbd..af62c6d6 100644 --- a/README.md +++ b/README.md @@ -96,12 +96,46 @@ doesn't land while they're unchanged: edit them, or accept a file as it is with `origin resolve `. `status` lists those left, and every new revision, `describe` included, keeps them. +## Serving + +A server is a node of its own, hosting repositories without a working +copy, and the authority of their targets: it runs their landing queues, +and packs their small objects once a few thousand pile up loose. + +```sh +origin repo create repos/demo # a repository the server orders `policy` and `main` of +origin serve # host the repositories over HTTP +``` + +Both read `origin-server.toml` (or `--config `), whose paths are +relative to it: + +```toml +listen = "127.0.0.1:7878" +node = "hosted" # the server's node name +key = "node.key" # its secret key, created if missing + +[repos] +demo = "repos/demo" +``` + +The HTTP API, under `/api/v1`, puts and fetches records in batches, lists +statements, revisions, targets and their logs, lands changes and targets, +and streams events by long-poll: `GET +/api/v1/repos//events?cursor=&wait=30s` answers as soon as there +are events after the cursor, with a JSON batch and the next cursor. +[`docs/openapi.json`](docs/openapi.json) describes it, and +[`origin-client`](crates/origin-client) is its Rust SDK. Nothing +authenticates callers yet. + ## Development ```sh just # format, lint, test, and audit dependencies just bench # micro-benchmarks just bench-git # origin against git, with hyperfine (docs/benchmarks.md) +just openapi # rewrite docs/openapi.json after changing the API +just serve # run `origin serve` ``` rustup installs the toolchain `rust-toolchain.toml` pins. The minimum diff --git a/apps/origin-src/Cargo.toml b/apps/origin-src/Cargo.toml index f9b70dab..f036de86 100644 --- a/apps/origin-src/Cargo.toml +++ b/apps/origin-src/Cargo.toml @@ -28,6 +28,7 @@ thiserror.workspace = true tokio.workspace = true toml.workspace = true tracing.workspace = true +tracing-subscriber.workspace = true utoipa.workspace = true utoipa-axum.workspace = true zstd.workspace = true diff --git a/apps/origin-src/src/cli.rs b/apps/origin-src/src/cli.rs index d204e3d0..87d4a5a5 100644 --- a/apps/origin-src/src/cli.rs +++ b/apps/origin-src/src/cli.rs @@ -1,5 +1,5 @@ //! The `origin` command line: argument parsing. The commands themselves are -//! methods of [`Workspace`], which print their output. +//! methods of [`Workspace`] and [`ServerConfig`], which print their output. use std::convert::Infallible; use std::env; @@ -14,6 +14,7 @@ use origin_shared::{Digest, Inputs, Kind, RepoPath, TargetName, Verdict}; use crate::config::UserConfig; use crate::oplog::Actor; +use crate::server::ServerConfig; use crate::workspace::{Annotated, Payload, Workspace}; /// A modern, git-compatible source control system. @@ -32,10 +33,32 @@ enum Command { #[arg(default_value = ".")] path: PathBuf, }, + /// Serve repositories over HTTP, as their authority. + Serve { + /// The server configuration file. + #[arg(short, long, default_value = "origin-server.toml")] + config: PathBuf, + }, + /// Manage the repositories a server hosts. + #[command(subcommand)] + Repo(RepoCommand), #[command(flatten)] Workspace(WorkspaceCommand), } +#[derive(Debug, Subcommand)] +enum RepoCommand { + /// Create a repository without a working copy for a server to host, + /// with the server's node the authority of `policy` and `main`. + Create { + /// Where to create it. + path: PathBuf, + /// The server configuration file. + #[arg(short, long, default_value = "origin-server.toml")] + config: PathBuf, + }, +} + /// Commands run in the repository containing the current directory. Those /// that read the working copy snapshot it first. Changes are named by a /// unique prefix of their id, or `@` for the working copy's. @@ -421,6 +444,13 @@ impl Cli { /// /// Fails if the command fails; the error is meant for the user. pub fn run(self) -> Result<()> { + match self.command { + Command::Serve { config } => return ServerConfig::load(&config)?.serve(), + Command::Repo(RepoCommand::Create { path, config }) => { + return ServerConfig::load(&config)?.create_repo(&path); + } + Command::Init { .. } | Command::Workspace(_) => {} + } let config = UserConfig::load()?; // The op log records the command line, without the program's name, // as text: an argument that isn't UTF-8, such as a path, is never @@ -435,6 +465,7 @@ impl Cli { Workspace::init(&path, config, &actor)?; } Command::Workspace(command) => command.run(config, &actor)?, + Command::Serve { .. } | Command::Repo(_) => unreachable!("run above"), } Ok(()) } diff --git a/apps/origin-src/src/config.rs b/apps/origin-src/src/config.rs index c8e9cdf4..d60f1fce 100644 --- a/apps/origin-src/src/config.rs +++ b/apps/origin-src/src/config.rs @@ -36,9 +36,6 @@ struct ConfigFile { } impl UserConfig { - /// The length of `node.key`: the raw secret key. - const KEY_LEN: usize = 32; - /// Loads the configuration from its directory. /// /// # Errors @@ -91,48 +88,65 @@ impl UserConfig { &self.node } - fn key_path(&self) -> PathBuf { - self.dir.join("node.key") + /// This node's key, generated and saved durably the first time. + /// + /// # Errors + /// + /// Fails like [`KeyFile::load`]. + pub fn node_key(&self) -> Result { + KeyFile(self.dir.join("node.key")).load() } +} - /// This node's key, generated and saved durably the first time. +/// A file holding a node's secret ed25519 key, readable only by its owner: +/// the user's `node.key`, or a server's. +#[derive(Clone, Debug)] +pub struct KeyFile(pub PathBuf); + +impl KeyFile { + /// The length of the file: the raw secret key. + const KEY_LEN: usize = 32; + + /// The key, generated and saved durably the first time. /// /// # Errors /// /// Fails if the key cannot be read, is malformed, or cannot be /// generated and saved. - pub fn node_key(&self) -> Result { - match self.read_key() { + pub fn load(&self) -> Result { + match self.read() { Err(ConfigError::Io { source, .. }) if source.kind() == io::ErrorKind::NotFound => { - self.create_key() + self.create() } result => result, } } - fn read_key(&self) -> Result { - let path = self.key_path(); - let bytes = fs::read(&path).map_err(|source| ConfigError::Io { + fn read(&self) -> Result { + let path = &self.0; + let bytes = fs::read(path).map_err(|source| ConfigError::Io { path: path.clone(), source, })?; let secret: [u8; Self::KEY_LEN] = bytes .try_into() - .map_err(|_| ConfigError::MalformedKey(path))?; + .map_err(|_| ConfigError::MalformedKey(path.clone()))?; Ok(NodeKey::from_bytes(&secret)) } /// Generates a key and saves it: written and synced under a temporary /// name, then linked into place, which fails if another process saved /// one first. That one is used instead. - fn create_key(&self) -> Result { + fn create(&self) -> Result { let io_error = |path: &Path| { let path = path.to_owned(); move |source| ConfigError::Io { path, source } }; - fs::create_dir_all(&self.dir).map_err(io_error(&self.dir))?; + let dir = self.0.parent().unwrap_or(Path::new(".")); + fs::create_dir_all(dir).map_err(io_error(dir))?; let key = NodeKey::generate().map_err(ConfigError::Random)?; - let temp = self.dir.join(format!(".node.key-{}", process::id())); + let name = self.0.file_name().unwrap_or_default().to_string_lossy(); + let temp = dir.join(format!(".{name}-{}", process::id())); // A crash can leave one behind, under a pid that a reboot hands out // again. Only this process uses the name. let _ = fs::remove_file(&temp); @@ -145,17 +159,15 @@ impl UserConfig { file.write_all(&key.to_bytes())?; Native::default().sync_file(&file) }) - .and_then(|()| fs::hard_link(&temp, self.key_path())); + .and_then(|()| fs::hard_link(&temp, &self.0)); // Best effort: a leftover is never read. let _ = fs::remove_file(&temp); match written { Ok(()) => {} - Err(error) if error.kind() == io::ErrorKind::AlreadyExists => return self.read_key(), + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => return self.read(), Err(source) => return Err(io_error(&temp)(source)), } - Native::default() - .sync_dir(&self.dir) - .map_err(io_error(&self.dir))?; + Native::default().sync_dir(dir).map_err(io_error(dir))?; Ok(key) } } @@ -167,16 +179,11 @@ mod tests { #[test] fn a_leftover_temporary_key_is_replaced() { let dir = tempfile::tempdir().unwrap(); - let name = PrincipalName::new("ada".to_owned()).unwrap(); - let config = UserConfig { - dir: dir.path().to_owned(), - user: name.clone(), - node: name, - }; + let file = KeyFile(dir.path().join("node.key")); fs::write(dir.path().join(format!(".node.key-{}", process::id())), b"").unwrap(); - let key = config.node_key().unwrap(); - assert_eq!(config.read_key().unwrap().to_bytes(), key.to_bytes()); + let key = file.load().unwrap(); + assert_eq!(file.read().unwrap().to_bytes(), key.to_bytes()); } } @@ -213,7 +220,7 @@ pub enum ConfigError { /// What is wrong. source: InvalidName, }, - /// `node.key` isn't a key. + /// A key file isn't a key. #[error("{} is not a node key", .0.display())] MalformedKey(PathBuf), /// The operating system has no randomness to generate a key with. diff --git a/apps/origin-src/src/server.rs b/apps/origin-src/src/server.rs index 5b2c3dae..140ed59b 100644 --- a/apps/origin-src/src/server.rs +++ b/apps/origin-src/src/server.rs @@ -1,10 +1,153 @@ -//! The repositories a server hosts. +//! `origin serve`: one node hosting repositories over HTTP. +//! +//! A server has a node key of its own, and is the authority of the targets +//! its repositories' policies name it for: `origin repo create` makes it the +//! authority of `policy` and `main`. The repositories have no working copy: +//! each is a store, in the directory the configuration names. use std::collections::BTreeMap; +use std::fs; +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::thread; +use std::time::Duration; +use anyhow::Context; +use origin_shared::PrincipalName; use origin_shared::api::{RepoName, RepoSummary}; +use serde::Deserialize; -use crate::service::{Caller, OriginService, ServiceError}; +use crate::config::KeyFile; +use crate::http::Api; +use crate::policy::Policy; +use crate::service::{Caller, Node, OriginService, ServiceError}; +use crate::store::Store; + +/// Server configuration, read from a TOML file: +/// +/// ```toml +/// listen = "127.0.0.1:7878" +/// node = "hosted" # the server's node name +/// key = "node.key" # its secret key, created if missing +/// +/// [repos] +/// origin = "repos/origin" # name = path +/// ``` +/// +/// Paths are relative to the file. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ServerConfig { + /// The address to listen on. Port 0 picks a free port. + pub listen: SocketAddr, + /// The server's node name. + pub node: PrincipalName, + /// The file holding the server's node key. + #[serde(default = "ServerConfig::default_key")] + pub key: PathBuf, + /// The repositories to serve, by name. + #[serde(default)] + pub repos: BTreeMap, +} + +impl ServerConfig { + fn default_key() -> PathBuf { + PathBuf::from("node.key") + } + + /// Reads the configuration, resolving its paths relative to it. + /// + /// # Errors + /// + /// Fails if the file cannot be read or is invalid. + pub fn load(path: &Path) -> anyhow::Result { + let content = + fs::read_to_string(path).with_context(|| format!("cannot read {}", path.display()))?; + let mut config: Self = toml::from_str(&content) + .with_context(|| format!("invalid configuration in {}", path.display()))?; + let base = path.parent().unwrap_or(Path::new(".")); + config.key = base.join(&config.key); + for repo in config.repos.values_mut() { + *repo = base.join(&*repo); + } + Ok(config) + } + + /// The server's node, with its key, generated the first time. + /// + /// # Errors + /// + /// Fails if the key cannot be read, or generated and saved. + pub fn node(&self) -> anyhow::Result { + Ok(Node { + name: self.node.clone(), + key: Arc::new(KeyFile(self.key.clone()).load()?), + }) + } + + /// `origin repo create`: creates an empty repository for this server + /// to host in `root`, with the server's node the authority of `policy` + /// and `main`. + /// + /// # Errors + /// + /// Fails if `root` isn't empty, or the key or repository cannot be + /// written. + pub fn create_repo(&self, root: &Path) -> anyhow::Result<()> { + let node = self.node()?; + let policy = Policy::initial(&node.name, &node.key.public()); + OriginService::create(root.to_owned(), node, &policy)?; + println!( + "Created a repository in {}: node:{} is the authority of `policy` and `main`", + root.display(), + self.node + ); + println!("Name it in the [repos] of the configuration to serve it"); + Ok(()) + } + + /// `origin serve`: serves the repositories until interrupted, logging + /// failures to stderr. Prints the address it listens on, which tells + /// callers that chose port 0 where to connect. + /// + /// # Errors + /// + /// Fails if a repository cannot be opened or the address bound. + pub fn serve(self) -> anyhow::Result<()> { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| "info".into()), + ) + .with_writer(std::io::stderr) + .init(); + let node = self.node()?; + let repositories = Repositories::open(self.repos, &node)?; + repositories.compact_in_background(); + let runtime = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .context("cannot start the server's runtime")?; + runtime.block_on(async { + let listener = tokio::net::TcpListener::bind(self.listen) + .await + .with_context(|| format!("cannot listen on {}", self.listen))?; + println!("Listening on http://{}", listener.local_addr()?); + axum::serve(listener, Api::router(repositories)) + .with_graceful_shutdown(async { + // If the signal handler cannot be installed, run until + // killed. + if let Err(error) = tokio::signal::ctrl_c().await { + tracing::warn!(%error, "cannot listen for Ctrl-C: serving until killed"); + std::future::pending::<()>().await; + } + }) + .await + .context("server failed") + }) + } +} /// The repositories a server hosts, each served by the server's node and /// kept open while it runs. @@ -14,6 +157,60 @@ pub struct Repositories { } impl Repositories { + /// How often [`Repositories::compact_in_background`] checks. + const COMPACT_EVERY: Duration = Duration::from_mins(1); + + /// Opens the repositories at the given paths, served by `node`. + /// + /// # Errors + /// + /// Fails if one has no repository. + pub fn open(repos: BTreeMap, node: &Node) -> anyhow::Result { + let repos = repos + .into_iter() + .map(|(name, path)| { + let service = OriginService::open(path, node.clone()) + .with_context(|| format!("cannot serve repository `{name}`"))?; + Ok((name, service)) + }) + .collect::>()?; + Ok(Self { repos }) + } + + /// Compacts each repository once enough loose objects pile up in it + /// (see [`Store::compact_if_due`]), checking every + /// [`Repositories::COMPACT_EVERY`] on a thread of its own, for as long + /// as the process runs. A failed compaction loses nothing, so it is + /// logged, and the next check tries again. + pub fn compact_in_background(&self) { + let stores: Vec<(RepoName, Store)> = self + .repos + .iter() + .map(|(name, service)| (name.clone(), service.store().clone())) + .collect(); + thread::spawn(move || { + loop { + thread::sleep(Self::COMPACT_EVERY); + for (repo, store) in &stores { + match store.compact_if_due() { + Ok(Some(compaction)) => tracing::info!( + %repo, + packed = compaction.packed, + merged = compaction.merged, + "compacted" + ), + Ok(None) => {} + Err(error) => tracing::error!( + %repo, + error = %anyhow::Error::from(error), + "compaction failed" + ), + } + } + } + }); + } + /// Hosts `service` as `name`. pub fn insert(&mut self, name: RepoName, service: OriginService) { self.repos.insert(name, service); diff --git a/apps/origin-src/tests/serve.rs b/apps/origin-src/tests/serve.rs new file mode 100644 index 00000000..0ad82b58 --- /dev/null +++ b/apps/origin-src/tests/serve.rs @@ -0,0 +1,69 @@ +//! End to end: `origin repo create` and `origin serve`, running the real +//! binary and talking to it through the SDK. + +use std::fs; +use std::io::{BufRead, BufReader}; +use std::process::{Child, Command, Stdio}; + +use origin_client::Client; +use origin_shared::api::RepoName; + +/// A running `origin serve`, killed when dropped. +struct Serve(Child); + +impl Drop for Serve { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} + +#[tokio::test] +async fn serves_the_repositories_it_created() { + let dir = tempfile::tempdir().unwrap(); + let config = dir.path().join("origin-server.toml"); + fs::write( + &config, + "listen = \"127.0.0.1:0\"\nnode = \"hosted\"\n[repos]\ndemo = \"repos/demo\"\n", + ) + .unwrap(); + let origin = |args: &[&str]| { + let mut command = Command::new(env!("CARGO_BIN_EXE_origin")); + command.args(args).arg("--config").arg(&config); + command + }; + + let created = origin(&["repo", "create"]) + .arg(dir.path().join("repos/demo")) + .output() + .unwrap(); + assert!( + created.status.success(), + "{}", + String::from_utf8_lossy(&created.stderr) + ); + assert!(dir.path().join("node.key").is_file(), "the server's key"); + + let mut child = origin(&["serve"]).stdout(Stdio::piped()).spawn().unwrap(); + let mut line = String::new(); + BufReader::new(child.stdout.take().unwrap()) + .read_line(&mut line) + .unwrap(); + let _serve = Serve(child); + let url = line.trim().strip_prefix("Listening on ").unwrap(); + + let client = Client::new(url); + let repos = client.repos().await.unwrap(); + assert_eq!(repos.len(), 1); + let targets = client + .repo(RepoName::new("demo").unwrap()) + .targets() + .await + .unwrap(); + assert!( + targets + .iter() + .all(|target| target.authority == Some("hosted".parse().unwrap())), + "the server orders the targets: {targets:?}" + ); +} diff --git a/justfile b/justfile index fabd5c89..4ba54cb8 100644 --- a/justfile +++ b/justfile @@ -33,6 +33,10 @@ deny: openapi: @UPDATE_OPENAPI=1 cargo nextest run --locked --package origin-src --test http openapi +# Serve repositories over HTTP (see `origin serve --help`). +serve *ARGS: + @cargo run --package origin-src --bin origin -- serve {{ARGS}} + # Micro-benchmarks of the hot paths (hashing, storage, snapshots). bench *ARGS: @cargo bench --locked --workspace -- {{ARGS}}