diff --git a/.github/workflows/docs-site.yml b/.github/workflows/docs-site.yml index 1ae7892e8..3ff3a0d13 100644 --- a/.github/workflows/docs-site.yml +++ b/.github/workflows/docs-site.yml @@ -14,6 +14,7 @@ on: paths: - 'docs/**' - 'website/**' + - 'extenddb.sample.toml' - 'Cargo.toml' - '.github/workflows/docs-site.yml' push: @@ -21,6 +22,7 @@ on: paths: - 'docs/**' - 'website/**' + - 'extenddb.sample.toml' - 'Cargo.toml' - '.github/workflows/docs-site.yml' workflow_dispatch: @@ -61,6 +63,9 @@ jobs: - name: Typecheck working-directory: website run: npm run typecheck + - name: Configuration reference matches extenddb.sample.toml + working-directory: website + run: npm run check:config - name: Build working-directory: website env: diff --git a/crates/backup-store/Cargo.toml b/crates/backup-store/Cargo.toml index 73be71b87..1d2344679 100644 --- a/crates/backup-store/Cargo.toml +++ b/crates/backup-store/Cargo.toml @@ -31,6 +31,11 @@ uuid = { workspace = true } # Failure-injection seam for the crate's own test suite; not part of the # supported API surface and never enabled by production consumers. test-util = [] +# `Serialize` on the four configuration types, for the tests of +# `extenddb-config` that pin `extenddb.sample.toml` to them. Off in the +# library build, so a value that can carry an endpoint's user information +# has no serialize path there. +serialize = [] [target.'cfg(unix)'.dependencies] libc = { workspace = true } diff --git a/crates/backup-store/src/config.rs b/crates/backup-store/src/config.rs index 59bcc0da9..5cca9a843 100644 --- a/crates/backup-store/src/config.rs +++ b/crates/backup-store/src/config.rs @@ -160,6 +160,7 @@ use serde::Deserialize; /// Which store implementation `[backup.store]` selects. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[serde(rename_all = "lowercase")] pub enum BackupStoreKind { /// Local directory store. The default: local development works with no @@ -193,6 +194,7 @@ impl BackupStoreKind { /// key (`store`) in its `[backup]` model rather than flattening it; that /// keeps one definition of these fields and unknown-field rejection on both. #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[serde(deny_unknown_fields)] pub struct BackupStoreConfig { /// Selected store kind; `filesystem` when absent. @@ -208,6 +210,7 @@ pub struct BackupStoreConfig { /// `[backup.store.filesystem]` settings. #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[serde(deny_unknown_fields)] pub struct FilesystemStoreConfig { /// Root directory for backup objects. Must exist at startup. @@ -219,6 +222,7 @@ pub struct FilesystemStoreConfig { /// user information, which `open` refuses but a log of the configuration /// written before `open` would otherwise carry. #[derive(Clone, PartialEq, Eq, Deserialize)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[serde(deny_unknown_fields)] pub struct S3StoreConfig { /// Destination bucket. diff --git a/crates/config/Cargo.toml b/crates/config/Cargo.toml index 841ffb944..ed4a0ea8c 100644 --- a/crates/config/Cargo.toml +++ b/crates/config/Cargo.toml @@ -26,4 +26,6 @@ anyhow = { workspace = true } tracing = { workspace = true } [dev-dependencies] +# The sample pin tests serialize the backup store configuration types. +extenddb-backup-store = { path = "../backup-store", features = ["serialize"] } tempfile = "3" diff --git a/crates/config/src/backup.rs b/crates/config/src/backup.rs index 098acd631..642f31c56 100644 --- a/crates/config/src/backup.rs +++ b/crates/config/src/backup.rs @@ -131,6 +131,7 @@ pub const DEFAULT_ROOT_DIR_NAME: &str = "backups"; pub const DEFAULT_SPOOL_DIR_NAME: &str = "backup-spool"; #[derive(Debug, Clone, Deserialize, PartialEq, Eq)] +#[cfg_attr(test, derive(serde::Serialize))] #[serde(deny_unknown_fields)] pub struct BackupConfig { /// Uncompressed bytes per data file; a file closes once it reaches this, diff --git a/crates/config/src/encryption.rs b/crates/config/src/encryption.rs index 3e63b7c3d..14091c678 100644 --- a/crates/config/src/encryption.rs +++ b/crates/config/src/encryption.rs @@ -3,13 +3,13 @@ //! The `[auth.encryption]` section. -use serde::{Deserialize, Deserializer}; +use serde::{Deserialize, Deserializer, Serialize}; use crate::expand_tilde; /// The `[auth.encryption]` section: the key-encryption key (KEK) file and the /// locked memory rule. -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct EncryptionConfig { /// Path of the KEK file. Not set: the server uses the catalog key in the diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 57802782c..bdad37eb5 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -13,7 +13,7 @@ use std::path::PathBuf; use extenddb_core::limits::LimitsConfig; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields)] @@ -51,7 +51,7 @@ pub struct AppConfig { } /// Configuration for import or export allowed paths. -#[derive(Debug, Clone, Default, Deserialize)] +#[derive(Debug, Clone, Default, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct ImportExportPathConfig { /// Allowed directories. All file paths are canonicalized and must resolve @@ -60,7 +60,7 @@ pub struct ImportExportPathConfig { pub paths: Vec, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct ServerConfig { #[serde(default = "default_bind_addr")] @@ -123,7 +123,7 @@ impl ServerConfig { /// /// TLS is always enabled. The `enabled` field is accepted for backward /// compatibility but the server refuses to start if set to `false`. -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct TlsConfig { /// TLS is mandatory. Accepted for backward compatibility; the server @@ -272,7 +272,7 @@ impl<'de> serde::Deserialize<'de> for StorageConfig { } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct AuthConfig { /// Auth provider: `"builtin"` (`SigV4` + IAM policies). The `"none"` value @@ -306,7 +306,7 @@ impl Default for AuthConfig { /// Each `*_seconds` field has a sensible default; operators only need to /// override values when they want to deviate from the docs. The configuration /// is static — values are read once at startup. -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct AuthCacheConfigToml { /// Master switch. When `false`, all caches operate in pass-through mode @@ -359,7 +359,7 @@ fn default_cache_max_entries() -> u64 { 10_000 } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct LoggingConfig { #[serde(default = "default_log_level")] @@ -565,6 +565,11 @@ mod encryption; pub use display::{MASK, build_config_entries, should_redact}; pub use encryption::EncryptionConfig; +#[cfg(test)] +mod sample_toml_support; +#[cfg(test)] +mod sample_toml_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/config/src/sample_toml_support.rs b/crates/config/src/sample_toml_support.rs new file mode 100644 index 000000000..29e6f506c --- /dev/null +++ b/crates/config/src/sample_toml_support.rs @@ -0,0 +1,339 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Test support for pinning `extenddb.sample.toml` to the configuration +//! structs. Included as a unit-test module by `extenddb-config` and, through +//! `#[path]`, by each storage backend crate, so there is one copy of the +//! sample's comment convention in the test code. +//! +//! Convention of the sample: every key is one commented line `# key = value`, +//! every section header is `[section]` (or `# [section]`), and every other +//! `#` line is prose. Uncommenting the key and header lines yields a TOML +//! document whose tables hold every key with its default. +//! +//! [`pin`] checks a section three ways: the table deserializes into the +//! struct; the set of keys equals the struct's field names, read from its +//! derived `Deserialize` so that `Option` fields and struct-valued fields +//! count too; and every key's value equals the value serde gives the field +//! when the key is missing, except the named example keys, whose value is +//! only type checked. A field added to a struct without a sample line fails +//! here, `Option`, struct or not. + +// Each including crate uses a subset of these helpers. +#![allow(dead_code)] + +use std::collections::BTreeSet; + +use serde::de::{DeserializeOwned, Error as _, Visitor}; +use toml::{Table, Value}; + +/// Workspace-root path of the sample, relative to any `crates/` crate. +const SAMPLE_PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../extenddb.sample.toml"); + +/// `# ident = value` with the comment marker removed, or `None`. +fn key_line(line: &str) -> Option { + let rest = line.strip_prefix("# ")?; + let (ident, _) = rest.split_once(" = ")?; + let is_ident = !ident.is_empty() + && ident.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') + && !ident.starts_with(|c: char| c.is_ascii_digit()); + is_ident.then(|| rest.to_owned()) +} + +/// `# [section]` with the comment marker removed, or `None`. +fn header_line(line: &str) -> Option { + let rest = line.strip_prefix("# ")?; + (rest.starts_with('[') && rest.ends_with(']')).then(|| rest.to_owned()) +} + +/// The sample with every key and header line uncommented, parsed as TOML. +pub fn sample() -> Table { + let text = + std::fs::read_to_string(SAMPLE_PATH).unwrap_or_else(|e| panic!("read {SAMPLE_PATH}: {e}")); + let uncommented: Vec = text + .lines() + .filter_map(|line| { + if line.starts_with('[') { + Some(line.to_owned()) + } else { + key_line(line).or_else(|| header_line(line)) + } + }) + .collect(); + uncommented + .join("\n") + .parse::() + .unwrap_or_else(|e| panic!("uncommented sample is not valid TOML: {e}")) +} + +/// The table at a dotted path such as `storage.postgres`, sub-tables included. +pub fn table_at<'a>(root: &'a Table, path: &str) -> &'a Table { + let mut table = root; + for part in path.split('.') { + table = table + .get(part) + .and_then(Value::as_table) + .unwrap_or_else(|| panic!("sample has no [{path}] section")); + } + table +} + +/// The table at a dotted path such as `storage.postgres`, without its +/// sub-tables, with every `~/` string expanded to `$HOME` (the server does +/// the same at startup) and with the named keys removed. +pub fn section(root: &Table, path: &str, remove: &[&str]) -> Table { + let table = table_at(root, path); + let home = std::env::var("HOME").expect("HOME is set"); + let mut out = Table::new(); + for (key, value) in table { + if value.is_table() || remove.contains(&key.as_str()) { + continue; + } + let value = match value.as_str().and_then(|s| s.strip_prefix("~/")) { + Some(rest) => Value::String(format!("{home}/{rest}")), + None => value.clone(), + }; + out.insert(key.clone(), value); + } + out +} + +/// A struct's field values as a TOML table without sub-tables. `None` fields +/// are absent, as the TOML serializer leaves them out. +pub fn defaults(value: &T) -> Table { + let mut table = Value::try_from(value) + .expect("struct serializes to TOML") + .as_table() + .cloned() + .expect("struct serializes to a table"); + table.retain(|_, v| !v.is_table()); + table +} + +/// A `Deserializer` that records the field list a derived `Deserialize` +/// passes to `deserialize_struct`, then stops. It needs no value of the +/// struct, so it works for `AppConfig`, whose `storage` field cannot be +/// built in this crate. +struct FieldRecorder<'a>(&'a mut Option<&'static [&'static str]>); + +impl<'de> serde::Deserializer<'de> for FieldRecorder<'_> { + type Error = serde::de::value::Error; + + fn deserialize_struct>( + self, + _name: &'static str, + fields: &'static [&'static str], + _visitor: V, + ) -> Result { + *self.0 = Some(fields); + Err(Self::Error::custom("field list recorded")) + } + + fn deserialize_any>(self, _visitor: V) -> Result { + Err(Self::Error::custom( + "not a struct with a derived Deserialize", + )) + } + + serde::forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map enum identifier ignored_any + } +} + +/// The field names of `T` as its derived `Deserialize` declares them: the +/// serde name of a renamed field, `Option` and struct-valued fields included, +/// `#[serde(skip)]` fields left out. The derive's list also holds every +/// `#[serde(alias)]` name, so `pin` cannot pass for a struct with an alias. +/// Without a sample line for the alias, `pin` reports the alias as missing. +/// With one, the derived `Deserialize` refuses the duplicate field. A struct +/// with a `#[serde(flatten)]` field passes no list, and this panics. +pub fn struct_fields() -> BTreeSet { + let mut fields = None; + let _ = T::deserialize(FieldRecorder(&mut fields)); + fields + .expect("T has a derived Deserialize") + .iter() + .map(|field| (*field).to_owned()) + .collect() +} + +/// Assert the sample section holds exactly the struct's fields, and that the +/// value of every field not named in `examples` equals the value a missing +/// key gives. +pub fn assert_pinned( + what: &str, + sample: &Table, + fields: &BTreeSet, + defaults: &Table, + examples: &[&str], +) { + let mut problems = Vec::new(); + for field in fields { + if !sample.contains_key(field) { + problems.push(format!( + "{field}: field of the struct, missing from the sample" + )); + } + } + for (key, actual) in sample { + if !fields.contains(key) { + problems.push(format!( + "{key}: in the sample but not a field of the struct" + )); + } else if !examples.contains(&key.as_str()) { + match defaults.get(key) { + Some(value) if value == actual => {} + Some(value) => problems.push(format!( + "{key}: sample has {actual}, a missing key gives {value}" + )), + None => problems.push(format!( + "{key}: a missing key gives None; list it as an example key" + )), + } + } + } + for example in examples { + assert!( + fields.contains(*example), + "[{what}] example key {example} is not a field of the struct" + ); + } + assert!( + problems.is_empty(), + "[{what}] in extenddb.sample.toml does not match the struct:\n {}", + problems.join("\n ") + ); +} + +/// Pin the sample section at `path` to `T`: the table deserializes into `T` +/// (a key the struct lacks fails here when `T` denies unknown fields), its +/// keys are exactly the field names of `T`'s derived `Deserialize`, and +/// every value equals the value serde fills in for a missing key, except for +/// the `examples`, whose sample line is an example rather than a default and +/// whose value is only type checked by the deserialization. The expected +/// values come from deserializing a table that holds only the `examples` +/// (the required keys are among them), so a `#[serde(default = ...)]` +/// function that disagrees with the sample fails here. A field the sample +/// writes as a sub-table (an `Option` of a struct, `None` when missing) is +/// left to the pin of that sub-table. Returns the field set it compared. +pub fn pin(root: &Table, path: &str, examples: &[&str]) -> BTreeSet +where + T: DeserializeOwned + serde::Serialize, +{ + let full = table_at(root, path).clone(); + let mut fields = struct_fields::(); + fields.retain(|field| !full.get(field).is_some_and(Value::is_table)); + let _: T = Value::Table(full.clone()) + .try_into() + .unwrap_or_else(|e| panic!("[{path}] of extenddb.sample.toml does not deserialize: {e}")); + let seed: Table = full + .iter() + .filter(|(k, _)| examples.contains(&k.as_str())) + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); + let expected: T = Value::Table(seed).try_into().unwrap_or_else(|e| { + panic!("[{path}] of extenddb.sample.toml: the example keys alone do not deserialize: {e}") + }); + assert_pinned( + path, + §ion(root, path, &[]), + &fields, + &defaults(&expected), + examples, + ); + fields +} + +/// [`pin`], then the same comparison with `T::default()`: the value of every +/// field when the file leaves the whole section out, which the parent +/// field's `#[serde(default)]` fills in. +pub fn pin_with_default(root: &Table, path: &str, examples: &[&str]) +where + T: Default + DeserializeOwned + serde::Serialize, +{ + let fields = pin::(root, path, examples); + assert_pinned( + &format!("{path} (section left out)"), + §ion(root, path, &[]), + &fields, + &defaults(&T::default()), + examples, + ); +} + +/// Assert the named keys of the sample section carry integer values (the +/// example value of a numeric key must not be a string). +pub fn assert_integers(root: &Table, path: &str, keys: &[&str]) { + let table = table_at(root, path); + for key in keys { + let value = table + .get(*key) + .unwrap_or_else(|| panic!("[{path}] has no key {key}")); + assert!( + value.is_integer(), + "[{path}] {key} must be an integer in the sample, found {value}" + ); + } +} + +/// Dotted paths of the keys whose description (the `#` lines directly above +/// the key line) ends with the marker sentence the generator reads, "No +/// default." or "No default of its own.", sorted. Follows the sample's +/// comment convention the same way the generator does (`NO_DEFAULT` in +/// `website/scripts/gen-config-reference.mjs`). +pub fn no_default_keys() -> Vec { + let text = + std::fs::read_to_string(SAMPLE_PATH).unwrap_or_else(|e| panic!("read {SAMPLE_PATH}: {e}")); + let mut section = String::new(); + let mut description: Vec<&str> = Vec::new(); + let mut found = Vec::new(); + for line in text.lines() { + if let Some(header) = + header_line(line).or_else(|| line.starts_with('[').then(|| line.to_owned())) + { + section = header.trim_matches(['[', ']']).to_owned(); + description.clear(); + } else if let Some(key) = key_line(line) { + let name = key.split_once(" = ").map_or(key.as_str(), |(k, _)| k); + let marker = description.join(" ").to_ascii_lowercase(); + if marker.ends_with("no default.") || marker.ends_with("no default of its own.") { + found.push(if section.is_empty() { + name.to_owned() + } else { + format!("{section}.{name}") + }); + } + description.clear(); + } else if line.trim().is_empty() { + description.clear(); + } else if let Some(rest) = line.strip_prefix('#') { + description.push(rest.trim()); + } + } + found.sort_unstable(); + found +} + +/// Names of the sub-tables of a table, sorted. +pub fn table_keys(table: &Table) -> Vec<&str> { + let mut keys: Vec<&str> = table + .iter() + .filter(|(_, v)| v.is_table()) + .map(|(k, _)| k.as_str()) + .collect(); + keys.sort_unstable(); + keys +} + +/// Names of the non-table keys of a table, sorted. +pub fn scalar_keys(table: &Table) -> Vec<&str> { + let mut keys: Vec<&str> = table + .iter() + .filter(|(_, v)| !v.is_table()) + .map(|(k, _)| k.as_str()) + .collect(); + keys.sort_unstable(); + keys +} diff --git a/crates/config/src/sample_toml_tests.rs b/crates/config/src/sample_toml_tests.rs new file mode 100644 index 000000000..131bb3afd --- /dev/null +++ b/crates/config/src/sample_toml_tests.rs @@ -0,0 +1,151 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Pins `extenddb.sample.toml` to the configuration structs of this crate, to +//! `LimitsConfig` and to the backup store structs this crate re-exports. Each +//! `[storage.]` section is pinned by its backend crate. +//! `docs/configuration.md` is generated from the sample, so a field added to +//! a struct without a sample line fails here before the page can go stale. + +use std::collections::BTreeSet; + +use crate::backup::{BackupConfig, BackupStoreConfig, FilesystemStoreConfig, S3StoreConfig}; +use crate::sample_toml_support as support; +use crate::{ + AppConfig, AuthCacheConfigToml, AuthConfig, EncryptionConfig, ImportExportPathConfig, + LoggingConfig, ServerConfig, TlsConfig, +}; +use extenddb_core::limits::LimitsConfig; + +/// The top-level keys and the sections of the sample are the fields of +/// `AppConfig`, under their serde names (`import` and `export` for +/// `import_config` and `export_config`). The sections are its eight +/// struct-valued fields; the tests below pin each one's keys. +#[test] +fn root_keys_are_the_app_config_fields() { + let root = support::sample(); + assert_eq!( + support::table_keys(&root), + [ + "auth", "backup", "export", "import", "limits", "logging", "server", "storage" + ] + ); + let keys: BTreeSet = root.keys().cloned().collect(); + assert_eq!(keys, support::struct_fields::()); +} + +/// Keys whose description carries the "no default" marker (the generator +/// shows them as none with an example) are exactly the keys the pin tests +/// exclude from value comparison plus the keys with no struct default at all: +/// `backend` (read by the custom `StorageConfig` deserializer), the three +/// optional top-level keys, the two required backend keys and the two +/// required backup store keys. +#[test] +fn no_default_marker_matches_the_example_keys() { + let mut expected: Vec<&str> = vec![ + // Excluded from value comparison in the pin tests. + "server.throttling_enabled", + "storage.postgres.catalog_pool_size", + "storage.mongodb.max_connections", + "storage.mongodb.max_catalog_connections", + "storage.cassandra.username", + "storage.cassandra.password", + "auth.encryption.key_file", + "backup.spool_path", + "backup.store.s3.region", + "backup.store.s3.endpoint", + // No struct default. + "storage.backend", + "docs_dir", + "import_export_root", + "max_import_bytes", + "storage.mongodb.connection_string", + "storage.cassandra.contact_points", + "backup.store.filesystem.path", + "backup.store.s3.bucket", + ]; + expected.sort_unstable(); + assert_eq!(support::no_default_keys(), expected); +} + +#[test] +fn storage_section_names_only_the_backend() { + let root = support::sample(); + let storage = support::table_at(&root, "storage"); + assert_eq!(support::scalar_keys(storage), ["backend"]); + assert_eq!( + support::table_keys(storage), + ["cassandra", "mongodb", "postgres", "sqlite"] + ); +} + +#[test] +fn server_section_matches_server_config() { + let root = support::sample(); + // `throttling_enabled` is `Option` with no default; the sample shows + // `false` as the example and its value is not compared. + support::pin_with_default::(&root, "server", &["throttling_enabled"]); +} + +#[test] +fn server_tls_section_matches_tls_config() { + let root = support::sample(); + support::pin_with_default::(&root, "server.tls", &[]); +} + +#[test] +fn auth_section_matches_auth_config() { + let root = support::sample(); + support::pin_with_default::(&root, "auth", &[]); +} + +#[test] +fn auth_cache_section_matches_auth_cache_config() { + let root = support::sample(); + support::pin_with_default::(&root, "auth.cache", &[]); +} + +#[test] +fn auth_encryption_section_matches_encryption_config() { + let root = support::sample(); + // `key_file` is `Option` with no default; the sample shows an + // example path and its value is not compared. + support::pin_with_default::(&root, "auth.encryption", &["key_file"]); +} + +#[test] +fn limits_section_matches_limits_config() { + let root = support::sample(); + support::pin_with_default::(&root, "limits", &[]); +} + +#[test] +fn logging_section_matches_logging_config() { + let root = support::sample(); + support::pin_with_default::(&root, "logging", &[]); +} + +#[test] +fn backup_section_matches_backup_config() { + let root = support::sample(); + // `spool_path` is `Option` with no default; the sample shows an + // example path and its value is not compared. + support::pin_with_default::(&root, "backup", &["spool_path"]); +} + +/// `path`, `bucket`, `region` and `endpoint` have no default, so the sample's +/// values for them are examples and are not compared. +#[test] +fn backup_store_sections_match_the_store_config() { + let root = support::sample(); + support::pin::(&root, "backup.store", &[]); + support::pin::(&root, "backup.store.filesystem", &["path"]); + support::pin::(&root, "backup.store.s3", &["bucket", "region", "endpoint"]); +} + +#[test] +fn import_and_export_sections_match_path_config() { + let root = support::sample(); + support::pin_with_default::(&root, "import", &[]); + support::pin_with_default::(&root, "export", &[]); +} diff --git a/crates/core/src/limits/mod.rs b/crates/core/src/limits/mod.rs index e7c78f6a4..d02ba89fc 100755 --- a/crates/core/src/limits/mod.rs +++ b/crates/core/src/limits/mod.rs @@ -1,6 +1,6 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 -use serde::Deserialize; +use serde::{Deserialize, Serialize}; /// The default `max_item_size_bytes` (400 KB as `DynamoDB` sizes items), the /// largest item the backup format's line cap is sized for: the backup job @@ -9,7 +9,7 @@ use serde::Deserialize; pub const DEFAULT_MAX_ITEM_SIZE_BYTES: usize = 409_600; /// All configurable limits with DynamoDB-compatible defaults. -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct LimitsConfig { #[serde(default = "default_max_item_size")] diff --git a/crates/storage-cassandra/src/config.rs b/crates/storage-cassandra/src/config.rs index 5bac3e38f..13b11b7e9 100644 --- a/crates/storage-cassandra/src/config.rs +++ b/crates/storage-cassandra/src/config.rs @@ -7,6 +7,7 @@ use serde::{Deserialize, Deserializer}; /// Cassandra storage backend configuration. #[derive(Debug, Clone, Deserialize)] +#[cfg_attr(test, derive(serde::Serialize))] pub struct CassandraStorageConfig { /// Cassandra contact points (host:port) pub contact_points: Vec, diff --git a/crates/storage-cassandra/src/lib.rs b/crates/storage-cassandra/src/lib.rs index 71f0f9bb7..d323ad868 100644 --- a/crates/storage-cassandra/src/lib.rs +++ b/crates/storage-cassandra/src/lib.rs @@ -40,6 +40,11 @@ pub mod operations; mod password_hash_store; pub(crate) mod propagation_hold; mod restore_engine; +#[cfg(test)] +#[path = "../../config/src/sample_toml_support.rs"] +mod sample_toml_support; +#[cfg(test)] +mod sample_toml_tests; mod snapshot_engine; mod stream_at_timestamp; mod stream_engine; diff --git a/crates/storage-cassandra/src/sample_toml_tests.rs b/crates/storage-cassandra/src/sample_toml_tests.rs new file mode 100644 index 000000000..2e1110134 --- /dev/null +++ b/crates/storage-cassandra/src/sample_toml_tests.rs @@ -0,0 +1,30 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Pins the `[storage.cassandra]` section of `extenddb.sample.toml` to +//! [`CassandraStorageConfig`](crate::config::CassandraStorageConfig). The other sections are pinned by +//! `extenddb-config`; `docs/configuration.md` is generated from the sample. + +use crate::config::CassandraStorageConfig; +use crate::sample_toml_support as support; + +#[test] +fn storage_cassandra_section_matches_the_struct() { + let root = support::sample(); + // `contact_points` is required and the sample shows an example, so its + // value is not compared. `username` and `password` are `Option` + // shown as examples. + support::pin::( + &root, + "storage.cassandra", + &["contact_points", "username", "password"], + ); + // The struct does not deny unknown fields, so a stray sub-table would + // pass deserialization; the section must have none. + let section = support::table_at(&root, "storage.cassandra"); + assert!( + support::table_keys(section).is_empty(), + "[storage.cassandra] has sub-tables the struct does not: {:?}", + support::table_keys(section) + ); +} diff --git a/crates/storage-mongodb/src/config.rs b/crates/storage-mongodb/src/config.rs index 7d35d83ed..55d7e380b 100644 --- a/crates/storage-mongodb/src/config.rs +++ b/crates/storage-mongodb/src/config.rs @@ -10,8 +10,10 @@ use serde::Deserialize; /// Deliberately does **not** derive `Serialize`: `connection_string` may carry /// `user:pass@` credentials, and a `Serialize` impl would let them leave the /// process on any serialize path. Matches the postgres backend, which derives -/// only `Debug, Clone, Deserialize`. +/// only `Debug, Clone, Deserialize`. The `cfg(test)` derive below exists for +/// the sample-pinning test and is absent from the library build. #[derive(Debug, Clone, Deserialize)] +#[cfg_attr(test, derive(serde::Serialize))] #[serde(deny_unknown_fields)] pub struct MongoStorageConfig { /// `MongoDB` connection string (mongodb://...) diff --git a/crates/storage-mongodb/src/lib.rs b/crates/storage-mongodb/src/lib.rs index ab9750f95..0820c2843 100644 --- a/crates/storage-mongodb/src/lib.rs +++ b/crates/storage-mongodb/src/lib.rs @@ -25,6 +25,11 @@ mod operations; mod password_hash_store; pub mod pushdown; mod restore_engine; +#[cfg(test)] +#[path = "../../config/src/sample_toml_support.rs"] +mod sample_toml_support; +#[cfg(test)] +mod sample_toml_tests; mod snapshot_engine; mod stream_at_timestamp; mod stream_engine; diff --git a/crates/storage-mongodb/src/sample_toml_tests.rs b/crates/storage-mongodb/src/sample_toml_tests.rs new file mode 100644 index 000000000..5b58170d2 --- /dev/null +++ b/crates/storage-mongodb/src/sample_toml_tests.rs @@ -0,0 +1,33 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Pins the `[storage.mongodb]` section of `extenddb.sample.toml` to +//! [`MongoStorageConfig`](crate::config::MongoStorageConfig). The other sections are pinned by +//! `extenddb-config`; `docs/configuration.md` is generated from the sample. + +use crate::config::MongoStorageConfig; +use crate::sample_toml_support as support; + +#[test] +fn storage_mongodb_section_matches_the_struct() { + let root = support::sample(); + // `connection_string` is required and the sample shows an example, so its + // value is not compared. `max_connections` and `max_catalog_connections` + // are `Option`; unset, the driver's pool size applies (the connection + // string's `maxPoolSize`, else 10), which no getter of the struct returns, + // so the sample shows production examples, written as integers. + support::pin::( + &root, + "storage.mongodb", + &[ + "connection_string", + "max_connections", + "max_catalog_connections", + ], + ); + support::assert_integers( + &root, + "storage.mongodb", + &["max_connections", "max_catalog_connections"], + ); +} diff --git a/crates/storage-postgres/src/config.rs b/crates/storage-postgres/src/config.rs index 7162b5daa..fe9df8e07 100755 --- a/crates/storage-postgres/src/config.rs +++ b/crates/storage-postgres/src/config.rs @@ -6,6 +6,7 @@ use serde::Deserialize; #[derive(Debug, Clone, Deserialize)] +#[cfg_attr(test, derive(serde::Serialize))] #[serde(deny_unknown_fields)] pub struct PostgresStorageConfig { #[serde(default = "default_connection_string")] diff --git a/crates/storage-postgres/src/lib.rs b/crates/storage-postgres/src/lib.rs index 885a8f925..d8d0e5fa8 100755 --- a/crates/storage-postgres/src/lib.rs +++ b/crates/storage-postgres/src/lib.rs @@ -28,6 +28,11 @@ mod operations; mod password_hash_store; mod pg_util; mod restore_engine; +#[cfg(test)] +#[path = "../../config/src/sample_toml_support.rs"] +mod sample_toml_support; +#[cfg(test)] +mod sample_toml_tests; mod snapshot_engine; #[doc(hidden)] pub use snapshot_engine::{ diff --git a/crates/storage-postgres/src/sample_toml_tests.rs b/crates/storage-postgres/src/sample_toml_tests.rs new file mode 100644 index 000000000..dfc4f49a3 --- /dev/null +++ b/crates/storage-postgres/src/sample_toml_tests.rs @@ -0,0 +1,29 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Pins the `[storage.postgres]` section of `extenddb.sample.toml` to +//! [`PostgresStorageConfig`](crate::config::PostgresStorageConfig). The other sections are pinned by +//! `extenddb-config`; `docs/configuration.md` is generated from the sample. + +use extenddb_storage::config::StorageConfig as _; + +use crate::config::PostgresStorageConfig; +use crate::sample_toml_support as support; + +#[test] +fn storage_postgres_section_matches_the_struct() { + let root = support::sample(); + // `catalog_pool_size` is `Option` that falls back to `pool_size`; the + // sample shows the fallback as the example, written as an integer, and + // the example is pinned to what the getter gives when the key is unset. + support::pin::(&root, "storage.postgres", &["catalog_pool_size"]); + let unset: PostgresStorageConfig = + toml::from_str("").expect("empty [storage.postgres] deserializes"); + assert_eq!( + support::table_at(&root, "storage.postgres") + .get("catalog_pool_size") + .and_then(toml::Value::as_integer), + Some(i64::from(unset.max_catalog_connections())), + "[storage.postgres] catalog_pool_size example must equal the fallback for an unset key" + ); +} diff --git a/crates/storage-sqlite/src/config.rs b/crates/storage-sqlite/src/config.rs index f10c05cf2..d00210194 100644 --- a/crates/storage-sqlite/src/config.rs +++ b/crates/storage-sqlite/src/config.rs @@ -36,6 +36,7 @@ use serde::Deserialize; /// of backups leaves at least half the pool to other requests; with 2 or 3 /// the one admitted backup holds two of them. #[derive(Debug, Clone, Deserialize)] +#[cfg_attr(test, derive(serde::Serialize))] #[serde(deny_unknown_fields)] pub struct SqliteConfig { #[serde(default = "default_path")] diff --git a/crates/storage-sqlite/src/lib.rs b/crates/storage-sqlite/src/lib.rs index 1d3a42763..462f2a3f6 100644 --- a/crates/storage-sqlite/src/lib.rs +++ b/crates/storage-sqlite/src/lib.rs @@ -185,6 +185,11 @@ mod password_hash_store; mod restore_engine; #[cfg(test)] mod restore_job_tests; +#[cfg(test)] +#[path = "../../config/src/sample_toml_support.rs"] +mod sample_toml_support; +#[cfg(test)] +mod sample_toml_tests; mod schema; // wasm32 calls only `database_file`; the module compiles its lock-taking // items off wasm32. diff --git a/crates/storage-sqlite/src/sample_toml_tests.rs b/crates/storage-sqlite/src/sample_toml_tests.rs new file mode 100644 index 000000000..532545156 --- /dev/null +++ b/crates/storage-sqlite/src/sample_toml_tests.rs @@ -0,0 +1,25 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Pins the `[storage.sqlite]` section of `extenddb.sample.toml` to +//! [`SqliteConfig`](crate::config::SqliteConfig). The other sections are pinned by +//! `extenddb-config`; `docs/configuration.md` is generated from the sample. + +use crate::config::SqliteConfig; +use crate::sample_toml_support as support; + +#[test] +fn storage_sqlite_section_matches_the_struct() { + let root = support::sample(); + // The sample documents the file build's default path. The `memory` + // feature changes the compiled-in default to `:memory:`, as the sample + // says, so that build checks the path's type only. + if cfg!(feature = "memory") { + let missing: SqliteConfig = + toml::from_str("").expect("empty [storage.sqlite] deserializes"); + assert_eq!(missing.path, ":memory:"); + support::pin::(&root, "storage.sqlite", &["path"]); + } else { + support::pin::(&root, "storage.sqlite", &[]); + } +} diff --git a/docs/build-docs.py b/docs/build-docs.py index f05a4a529..a5ac62a4e 100755 --- a/docs/build-docs.py +++ b/docs/build-docs.py @@ -89,6 +89,8 @@ "docs/manuals/13-event-ticketing-demo.md"), (19, "backup-and-restore", "Backup and Restore", "usage", "docs/manuals/14-backup-and-restore.md"), + (20, "configuration", "Configuration", "reference", + "docs/configuration.md"), ] diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 000000000..85567c198 --- /dev/null +++ b/docs/configuration.md @@ -0,0 +1,230 @@ +--- +description: "Every key of extenddb.toml, its default and what it controls, generated from extenddb.sample.toml." +custom_edit_url: https://github.com/ExtendDB/extenddb/edit/main/extenddb.sample.toml +--- + +# Configuration + +This page is generated from [`extenddb.sample.toml`](https://github.com/ExtendDB/extenddb/blob/main/extenddb.sample.toml) by `npm run gen:config` in `website/`; edit the sample, not this file. Tests in the `extenddb-config` crate and in each storage backend crate compare the sample with the configuration structs, so a key listed here exists in the code with the default shown. + +The server reads `extenddb.toml` (or the file named by `--config`) at startup. Scalar keys can also be set through an environment variable: the name is `EXTENDDB__` followed by the key path in upper case with `__` between levels, for example `EXTENDDB__SERVER__PORT=9000` or `EXTENDDB__STORAGE__POSTGRES__CONNECTION_STRING="postgresql://..."`. The list keys (`import.paths`, `export.paths`, `storage.cassandra.contact_points`) and the numeric keys of `[storage.sqlite]` and `[storage.cassandra]` are file only. Precedence, highest first: environment variables, the configuration file, built-in defaults; `extenddb serve --port` overrides `server.port` on top of all three. + +The keys below are static: a change takes effect at the next server start. Settings that change on a running server (log level, control plane delay, throttling at runtime) are set with `extenddb settings set` and are listed under [Runtime Settings](./manuals/05-admin-guide.md#runtime-settings) in the administration guide. + +## Top-level keys + +These keys sit at the top level and must appear before the first [section] header of the file. A top-level key placed after a header lands inside that section. Every section except [storage], [storage.cassandra] and the sections of the other backends then refuses to start the server with "unknown field" and the key named. [storage] reads only `backend` and the section of the binary's own backend, and drops any other key without an error. A binary does not read the sections of the other backends. [storage.cassandra] ignores a key it does not know. + +| Key | Default | Description | +|-----|---------|-------------| +| `docs_dir` | none | Path to the rendered documentation directory (HTML and PDF files) produced by `python3 docs/build-docs.py`. When set, the web console serves the documentation at /console/docs; when absent, those routes show a "not configured" message. `extenddb init` discovers this directory when it exists. Example: `docs_dir = "/path/to/docs/rendered"` | +| `max_import_bytes` | none | Maximum import file size in bytes. When set, it replaces `limits.max_import_file_bytes`, which carries the 10 GB default. Example: `max_import_bytes = 10737418240` | +| `import_export_root` | none | Deprecated: a single root for both import and export. It fills whichever of the [import] and [export] path lists is empty: with both lists filled it does nothing, with one filled it supplies the other, and with both empty (the sections as this file ships them) it makes the import and export roots the same directory. The server logs which of those happened at startup. Prefer the sections: this key will be removed. Example: `import_export_root = "/var/lib/extenddb/data"` | + +## `[server]` + +The listening socket and the per-server behavior that is fixed at startup. The management web console is served at /console/ on the same address and port as the DynamoDB API and needs no configuration of its own. + +| Key | Default | Description | +|-----|---------|-------------| +| `bind_addr` | `"127.0.0.1"` | Network interface to bind. The default listens on loopback only; bind 0.0.0.0 to accept connections from other hosts. A dev-mode build refuses a non-loopback address unless `EXTENDDB_DEV_ALLOW_ANY_BIND=1` is set in its environment, as the dev image sets it, because a container's published port decides exposure there. | +| `port` | `18443` | Listening port for the DynamoDB API, the management API and the console. | +| `region` | `"us-east-1"` | AWS region used when generating Amazon Resource Names (ARNs). Requests must carry a credential scope for this region; any other region is rejected with `InvalidSignatureException`, as the service rejects a scope for a region other than the endpoint's. Every backup ARN the server issues carries it, so the value must stay within [a-z0-9-]. Under a value outside that class the server logs a warning at startup and refuses `CreateBackup` with a `ValidationException` naming `server.region`, since no backup ARN can be formed; a backup taken earlier under such a region keeps an ARN that `DescribeBackup`, `DeleteBackup` and `RestoreTableFromBackup` refuse as not valid. A backup ARN of the caller's account in another region is resolved in the server's region first, then as written. See the [upgrade manual](./manuals/07-upgrade-manual.md) before changing it on a deployment that has backups. | +| `run_dir` | `"~/.extenddb/run"` | Directory for runtime files (the process ID file). A leading ~ expands to $HOME. When HOME is unset the default is /tmp. | +| `throttling_enabled` | none | Provisioned throughput throttling via in-memory token buckets. When true, tables with provisioned capacity are rate limited to their configured read capacity units (RCU) and write capacity units (WCU), on-demand tables use the default ceilings (12,000 RCU and 4,000 WCU), and the account-level aggregate limits in [limits] apply. This key sets the value the server starts with; once the `throttling_enabled` runtime setting has been written with `extenddb settings set`, the runtime setting takes precedence. Unset means throttling is off. Example: `throttling_enabled = false` | +| `request_timeout_secs` | `30` | Seconds a connection may take to deliver its request headers, and seconds a request body may stall without delivering data, before the server closes the connection (a stalled body gets HTTP 408). Bounds how long a stalled or malicious client can hold a connection open. A connection that is accepted, or that completes the TLS handshake, and then sends no byte is closed after the same number of seconds, as is one that sends only part of the 24-byte HTTP/2 preface. The same value bounds how long an idle keep-alive connection waits for its next request, so SDK connection pools see idle connections closed after it (they reopen transparently), and it is the HTTP/2 keep-alive PING interval and timeout, so a stalled HTTP/2 connection is closed within twice the value. Must be at least 1 and at most 86400 (a day); the server refuses a larger value at startup, because the per-connection timers add it to the current instant and a value near `u64::MAX` overflows that addition. | + +## `[server.tls]` + +Transport Layer Security (TLS) is mandatory. `extenddb init` generates a self-signed certificate; replace it with one signed by a certificate authority for production use. + +| Key | Default | Description | +|-----|---------|-------------| +| `enabled` | `true` | Accepted for backward compatibility. The server refuses to start when this is set to false. A dev-mode build serves plain HTTP on loopback and ignores this key. | +| `cert_path` | `"~/.extenddb/tls/cert.pem"` | Path to the certificate file in Privacy Enhanced Mail (PEM) format. A leading ~ expands to $HOME. When HOME is unset the default is /tmp/extenddb-cert.pem. | +| `key_path` | `"~/.extenddb/tls/key.pem"` | Path to the private key file in PEM format. A leading ~ expands to $HOME. When HOME is unset the default is /tmp/extenddb-key.pem. | + +## `[storage]` + +Each ExtendDB binary contains exactly one storage backend and reads the [storage.<backend>] section with that backend's name. The other [storage.\*] sections are ignored, so one file can carry all four. ExtendDB owns the collections, tables and indexes of its catalog and data databases. A change to them, such as an added index, is not supported and can make a later migration fail. + +| Key | Default | Description | +|-----|---------|-------------| +| `backend` | none | Name of the storage backend this file is written for: "postgres", "sqlite", "mongodb" or "cassandra". The key is optional; when present it is checked against the binary's compiled-in backend and the server refuses to start on a mismatch. Example: `backend = "postgres"` | + +## `[storage.postgres]` + +The connection string points to the catalog database, which stores table metadata and the connection information for the data database. Several independent catalogs can coexist on one PostgreSQL instance. + +Connection budget: `pool_size` sizes two pools, one against the catalog database and one against the data database, which `extenddb init` creates separately. Total PostgreSQL connections used: 2 \* `pool_size` + `catalog_pool_size` + `[backup] max_concurrent_jobs` (one claim connection per running backup or restore job), plus one per vector index build running on this server and one while a schema migration runs. PostgreSQL's max_connections is per cluster, not per database, so both pools draw on the same budget. The defaults need 64 of PostgreSQL's default 100. The claim connections, the index build session and the migration connection sit outside every pool. A build's ownership lock is session scoped, so the build holds a session that ends with it; a pooled connection would return to the pool still holding the lock. A job's claim is a session-level advisory lock held the same way. The migration lock is transaction scoped and runs in one explicit transaction, so it needs a connection pinned to one PostgreSQL backend until COMMIT; a transaction-pooling proxy could otherwise move it between backends. The administration guide's section on the [connection budget and restores](./manuals/05-admin-guide.md#postgresql-connection-budget-and-restores) describes how backup and restore jobs draw on this pool. + +| Key | Default | Description | +|-----|---------|-------------| +| `connection_string` | see description | Connection string for the catalog database. For production add `?sslmode=require` and a password of your own. Default: `connection_string = "postgresql://extenddb:extenddb-local-dev@localhost:5432/extenddb_catalog"` | +| `pool_size` | `20` | Maximum concurrent connections in each of the two data-operation pools. A value under 2 \* `[backup] max_concurrent_jobs` + 10 (18 with the default of 4 jobs, 12 at the least) is raised to that at startup with a warning naming both numbers. Increase for higher concurrency and raise PostgreSQL's max_connections to at least 2 \* `pool_size` + `catalog_pool_size` + `max_concurrent_jobs` + the number of vector index builds you expect to overlap. | +| `catalog_pool_size` | none | Maximum connections for the management and catalog pool (authorization, Identity and Access Management (IAM), console). Raised to the same 2 \* `max_concurrent_jobs` + 10 floor with a warning. With auth enabled each DynamoDB request makes concurrent authorization queries, so size this to match the expected request concurrency. Falls back to `pool_size` when absent. Example: `catalog_pool_size = 20` | + +## `[storage.sqlite]` + +Developer mode backend. Select it with `extenddb init --backend sqlite`. The database path can be given at init time (`extenddb init --sqlite-path `, written into this file) or set here; at serve time the `EXTENDDB__STORAGE__SQLITE__PATH` environment variable overrides it. + +| Key | Default | Description | +|-----|---------|-------------| +| `path` | `"extenddb.sqlite"` | Database file. The default shown is the file build's. A `sqlite-memory` build defaults to ":memory:". A relative path is resolved against the working directory when the configuration loads, before `serve` daemonizes. ":memory:" selects an ephemeral in-memory database whose data is lost on shutdown and whose catalog is new at every start: with [backup.store] configured the server adopts the root an earlier in-memory catalog owned and syncs its backups into the new catalog before it serves, within 60 s (an S3 store in the reconciler's first cycle; a sync not finished in 60 s, or one that met a store or catalog error on a prefix, runs again in the next cycle). Every run lists the root from its first key, so the startup sync completes only while listing the whole root fits in 60 s; past that it stays pending, is retried every cycle, and the backups beyond what a run reaches are not served. A run holds the whole listing of the root in memory (one entry per object) until it ends, and a listing that outlasts 60 s reaches no prefix. On a filesystem store a run abandoned at the 60 s bound does not stop its listing: the walk of the root runs to its end on the blocking pool, holding the listing it builds, and no second walk starts beside it; until it ends, every check of the store is refused at once ("an abandoned startup sync's store call has not returned") and records the store `unreachable`, so CreateBackup, DeleteBackup and restores are refused and the sync does not run; the first reconciler cycle after the walk ends finds the store healthy and runs the sync again, from the first key. A root too large to list within 60 s is never synced by an in-memory server: give it a smaller root, or a durable catalog. On a filesystem store the server does not answer, `/health` included, until the startup sync ends (a liveness probe with a short timeout restarts such a server on a large root, each start syncing from the first key), and a signal then ends the process at once. Until the log line `startup sync of the in-memory catalog: N backup(s) adopted` the earlier backups answer `BackupNotFoundException`, although `/health` may already report the store healthy; a prefix that line reports as having met a store or catalog error stays so until a later cycle's line. Each run names the prefixes it skipped for a store or catalog error at WARN; until one run has listed the whole root and logged its line of counts, each run also names every other prefix it skipped at INFO (so the reasons reach the log when the first run was cut at the bound or stopped by an error), and a later run of a sync left pending logs those at DEBUG, so a root of many backups with one that fails costs one WARN line and the line of counts per cycle. A server killed inside a DeleteBackup (between the DELETING write and the manifest's deletion), or restarted after a DeleteBackup whose manifest deletion failed, serves that backup again at its next start, since the startup sync adopts the complete prefix; a prefix a stopped server had not finished writing or deleting (a killed CreateBackup, a failed backup whose prefix deletion had not finished, a deletion cut after its manifest) stays under the root with no row to drive its deletion (the next start's sync skips a prefix without its manifest); the startup sync names each such prefix in its log line `backup store startup sync: not adopted: not a complete backup: ...`. Delete such a prefix by hand, since every `extenddb backup` command refuses an in-memory database, but only one that has no `extenddb-manifest.json` and whose backup `ListBackups` does not return: a CreateBackup the running server is still writing has no manifest until its last put either, and its row is in `ListBackups` (status CREATING). Start a new in-memory server only after the old one has exited: one started beside it adopts the root while the old one still acts on it until a later check finds it adopted, its deletion fence (the store identity paragraph of the administration guide's backup store section) excepted. A root that an in-memory server of an earlier development build wrote has an `extenddb-store.json` without `ephemeral_catalog` (no release wrote one), which reads as a durable catalog's: the server finds the root owned by another catalog, its store stays unhealthy, and no command can adopt it. Remove that `extenddb-store.json`; the next start writes a new one (a new store id) and adopts the backups under the root. Every `extenddb backup` command refuses an in-memory database. | +| `pool_size` | `10` | Connection pool size. Writes are serialized by the engine whatever the size. A file database raises a value of 1 to 2 and logs it at info (`SQLite pool_size 1 raised to 2 for a file-backed database: ...`), because a backup holds one reader connection for its whole duration while its batches write through another; use 3 or more so a running backup does not contend with ordinary requests. Besides the `[backup] max_concurrent_jobs` bound, the process runs at most `pool_size` / 2 - 1 backups at once (between 1 and 16; 4 with the default) and refuses a CreateBackup that finds no slot free at once with LimitExceededException, without waiting; a file database raises a smaller `pool_size` to 2 \* (`max_concurrent_jobs` + 1), at most 34, so that bound refuses no job `max_concurrent_jobs` admits. | + +## `[storage.mongodb]` + +MongoDB requires a replica set, even a single-node one, because conditional writes and transactions use multi-document transactions. + +| Key | Default | Description | +|-----|---------|-------------| +| `connection_string` | none | MongoDB connection string. Required. Example: `connection_string = "mongodb://localhost:27017/?replicaSet=rs0"` | +| `max_connections` | none | Maximum size of the data connection pool. Unset leaves the driver's pool size: the connection string's `maxPoolSize` when it has one, else the driver's default of 10 connections per server. The example is a production value. Example: `max_connections = 50` | +| `max_catalog_connections` | none | Shared catalog and authorization pool for management and authorization traffic; size it for their combined concurrency. Unset leaves the driver's pool size, as for `max_connections`. The example is a production value. Example: `max_catalog_connections = 20` | +| `transaction_read_concern` | `"snapshot"` | Read concern for the multi-document transactions behind conditional writes, TransactWriteItems, TransactGetItems and idempotency tokens. Accepted values: "snapshot", "majority" and "local". "snapshot" keeps the single point-in-time guarantee. Some MongoDB-wire-compatible servers reject "snapshot" transactions with CommandNotSupported (code 115); set "majority" or "local" only when required. Both lose the point-in-time guarantee and "local" may read data that is later rolled back after a failover. The server logs a startup warning for either. | + +## `[storage.cassandra]` + +Cassandra backend. Keyspaces are created with NetworkTopologyStrategy in the configured datacenter. One connection pool serves catalog and data traffic. + +| Key | Default | Description | +|-----|---------|-------------| +| `contact_points` | none | Contact points as host:port strings. Required. Example: `contact_points = ["localhost:9042"]` | +| `username` | none | Username for authentication. Omit for an unauthenticated cluster. Example: `username = "cassandra"` | +| `password` | none | Password for authentication. Omit for an unauthenticated cluster. Example: `password = "cassandra"` | +| `keyspace_prefix` | `"extenddb"` | Prefix of the keyspaces the backend creates. | +| `replication_factor` | `3` | Replication factor for the keyspaces the backend creates. | +| `datacenter` | `"datacenter1"` | Datacenter name used in NetworkTopologyStrategy. | +| `max_connections` | `10` | Maximum connections per host. | + +## `[auth]` + +Authentication is mandatory. Run `extenddb init` to create the encryption key and the admin user before the first start. + +| Key | Default | Description | +|-----|---------|-------------| +| `provider` | `"builtin"` | Auth provider. "builtin" verifies Signature Version 4 (SigV4) signatures against the local credential store and evaluates IAM policies. The server refuses to start with "none". | + +## `[auth.cache]` + +In-memory stale-while-revalidate caches sit between the request path and the catalog database. Without them each request issues about six catalog queries during authentication and authorization; with them the steady state is close to none. Changes made through this server's admin API propagate at once by write-through invalidation. Changes made elsewhere (other nodes of a multi-node deployment, or direct database writes) take up to `ttl_seconds` to become visible. The server refuses to start when `ttl_seconds` is 0, when `soft_ttl_seconds` or `negative_ttl_seconds` exceeds `ttl_seconds`, or when `max_entries` is 0. The administration guide's section on [cache statistics and invalidation timing](./manuals/05-admin-guide.md#auth-cache-statistics-and-invalidation-timing) covers the metrics endpoint. + +| Key | Default | Description | +|-----|---------|-------------| +| `enabled` | `true` | Kill switch. When false, the cache wrappers skip lookup, insert and eviction and forward every request to the catalog. Use it during incident response. | +| `ttl_seconds` | `60` | Hard time to live in seconds. Entries older than this trigger a fresh load that the request waits for. | +| `soft_ttl_seconds` | `30` | Stale-but-usable threshold in seconds. Entries older than this are returned at once while a background task refreshes them. Set it equal to `ttl_seconds` to disable refresh-ahead. | +| `negative_ttl_seconds` | `5` | Time to live in seconds for negative results ("not found"). Short so newly created entities become usable quickly. | +| `max_entries` | `10000` | Maximum entries per cache; least recently used entries are evicted beyond it. | + +## `[auth.encryption]` + +Where the key that encrypts stored secrets comes from. Without this section the server uses the catalog key in the `encryption_key` settings row, as `extenddb init` created it. The release before this one refuses an `[auth.encryption]` table, even an empty one, so the header stays commented until `key_file` is set. The administration guide's [Encryption Key](./manuals/05-admin-guide.md#encryption-key) section gives the procedure, the file format, the ownership and mode the file must have, and the delivery routes. + +| Key | Default | Description | +|-----|---------|-------------| +| `key_file` | none | Path of the key-encryption key (KEK) file. When it is set, the server unwraps the data encryption key (DEK) from the `encryption_key_ring` settings row with the KEK in this file. Set it only after `extenddb encryption-key switch --yes` completes. A leading `~` expands as in the TLS key path. The configuration refuses a path that is relative after that expansion, because `serve` changes its working directory to `/` when it detaches. An in-memory SQLite catalog refuses this key. Example: `key_file = "/etc/extenddb/kek"` | +| `require_locked_memory` | `true` | With `key_file` set, refuse to start when the locked key store that holds the DEK and the cached signing keys cannot lock its memory. The refusal names the memlock limit it needs. false turns the refusal into a warning. Without `key_file` the server warns and starts in either case. | + +## `[limits]` + +The defaults match the DynamoDB service quotas. Override them only to test edge cases. + +| Key | Default | Description | +|-----|---------|-------------| +| `max_item_size_bytes` | `409600` | Maximum size of one item in bytes, attribute names and values included. | +| `max_partition_key_size_bytes` | `2048` | Maximum size of a partition key value in bytes. | +| `max_sort_key_size_bytes` | `1024` | Maximum size of a sort key value in bytes. | +| `max_tables_per_account` | `2500` | Shown on the console settings page. Not enforced: CreateTable does not count the account's tables. | +| `max_gsis_per_table` | `20` | Maximum number of global secondary indexes per table. | +| `max_lsis_per_table` | `5` | Maximum number of local secondary indexes per table. | +| `list_tables_max_per_page` | `100` | Largest Limit value ListTables accepts, and its page size when Limit is absent. | +| `max_table_name_length` | `255` | Maximum length of a table name in characters. | +| `min_table_name_length` | `3` | Minimum length of a table name in characters. | +| `per_table_max_rcu` | `40000` | Value DescribeLimits reports as TableMaxReadCapacityUnits. CreateTable and UpdateTable do not enforce it. | +| `per_table_max_wcu` | `40000` | Value DescribeLimits reports as TableMaxWriteCapacityUnits. CreateTable and UpdateTable do not enforce it. | +| `per_account_max_rcu` | `80000` | Maximum aggregate read capacity units across the account, enforced when throttling is enabled and reported by DescribeLimits. | +| `per_account_max_wcu` | `80000` | Maximum aggregate write capacity units across the account, enforced when throttling is enabled and reported by DescribeLimits. | +| `allow_multipart_table_keys` | `false` | Preview extension: allow multi-part (composite) keys on base tables. When false, base tables follow the DynamoDB rule of one HASH key and at most one RANGE key. Global secondary indexes allow multi-part keys regardless. | +| `max_attribute_name_bytes` | `65535` | Maximum attribute name size in bytes. | +| `max_expression_tokens` | `4096` | Maximum number of tokens in one expression (condition, update, projection or key condition). | +| `max_expression_length_bytes` | `4096` | Maximum size of one expression string in bytes, measured on the text before #name and :value substitution. | +| `max_expression_depth` | `150` | Maximum nesting depth of one expression. In a ConditionExpression or FilterExpression a parenthesized group, a NOT and a `size` operand each nest one level. AND and OR do not. In an UpdateExpression a parenthesized value and a function call each nest one level. | +| `max_policy_document_bytes` | `6144` | Accepted but not read. The policy document size limit is fixed at 6,144 bytes, measured before JSON parsing. | +| `max_import_file_bytes` | `10737418240` | Maximum import file size in bytes (10 GB). The top-level `max_import_bytes` key replaces this value when set. | +| `max_import_item_count` | `10000000` | Maximum number of items in one import. | +| `max_export_item_count` | `10000000` | Maximum number of items in one export. | +| `enforce_reserved_keywords` | `true` | Reject bare reserved keywords in expressions, as the service does. | + +## `[logging]` + +In daemon mode output goes to syslog (facility daemon, ident `extenddb`); read it with `journalctl -t extenddb`. With `extenddb serve --foreground` output goes to stderr for the process supervisor. The level set here is the one the server starts with; the `log_level` runtime setting changes it without a restart. + +| Key | Default | Description | +|-----|---------|-------------| +| `level` | `"info"` | Log level: "trace", "debug", "info", "warn" or "error". | +| `format` | `"pretty"` | Log format: "pretty" for humans or "json" for structured output. | + +## `[backup]` + +The knobs backup and restore jobs and the reconciler read. Every key has a default, so the section may be left out. The server refuses to start when `stale_job_after_secs` is under three heartbeat periods, when `data_file_target_bytes` is under 32 MiB, when `max_concurrent_jobs` is 0 or over 1024, when `heartbeat_interval_secs` or `reconcile_interval_secs` is 0, or when `failed_row_retention_secs` is under `stale_job_after_secs`. This section and [backup.store] below are the reference for the keys; the [Backup and Restore manual](./manuals/14-backup-and-restore.md) covers the strategy, the recovery point and time, securing the store, the restore drill and catalog-loss recovery, and the administration guide's section on the backup store covers the `extenddb backup` commands. + +| Key | Default | Description | +|-----|---------|-------------| +| `data_file_target_bytes` | `67108864` | Uncompressed bytes per backup data file, read by the store-backed backup writer. Minimum 33554432 (32 MiB), the cap on one line of a data file: a data file closes at the first item that takes it to or past this size, so it exceeds the size by less than one line. | +| `heartbeat_interval_secs` | `15` | The job heartbeat timer, in seconds. The store-backed backup job heartbeats every max(`heartbeat_interval_secs`, 15) s and starts no store write unless a beat confirmed its claim within two periods or a beat is still in flight (on SQLite a beat waits behind any writer holding the engine write lock, a GSI backfill say, for as long as it holds it, and a backup goes on writing meanwhile; on the other backends a beat in flight does not count), the claim's insert counting as the first beat; the in-catalog backup and restore paths heartbeat every 15 s whatever this says. The staleness floor below is computed from the larger of the two. | +| `stale_job_after_secs` | `300` | Heartbeat age in seconds after which a job's owner is dead (on PostgreSQL, once the owner's claim session has ended as well) and the reconciler resolves the job: a dead backup job with a complete manifest under its prefix is AVAILABLE, one without is FAILED and its prefix deleted; a dead in-catalog restore is FAILED and its target removed; a dead store-backed restore is resumed from its recorded progress (the differences document's restore-interruption row). After the same age a maintenance command that died (killed, or its catalog connection lost) no longer holds the maintenance claim, on PostgreSQL too (until then the next one fails at once, naming the holder). Must be at least three heartbeat periods, where the period is the larger of `heartbeat_interval_secs` and the 15 s the in-catalog jobs heartbeat at, so 45 at the least. On SQLite a heartbeat waits for the engine write lock like any writer, so a value near the floor can declare a live job dead on a busy file; keep a margin above the floor. | +| `failed_row_retention_secs` | `604800` | How long FAILED and DELETED backup rows of the configured store are kept once their objects are gone, in seconds (7 days); `extenddb backup list --failed` prints the FAILED ones with their reason. At least `stale_job_after_secs`: the reconciler deletes a stopped job's late object only under its row, so the row outlives the window in which that job can still write; a smaller value is refused at startup. | +| `reconcile_interval_secs` | `60` | The reconciler's cycle, in seconds; it also runs once at startup. Each cycle checks the store, resolves backup and restore jobs whose owner is dead, finishes deletions, deletes the objects of FAILED backups once their heartbeat is older than `stale_job_after_secs`, and removes tombstones past `failed_row_retention_secs` (the differences document's restore-interruption row lists the duties). | +| `max_concurrent_jobs` | `4` | Backup and restore jobs this instance runs at once, the in-catalog creates and restores included; at most 1024. A request that finds every slot held waits up to 30 s for one and is then refused with LimitExceededException. On PostgreSQL each running job holds one claim connection outside the pools, and `pool_size` and `catalog_pool_size` are raised to at least 2 \* `max_concurrent_jobs` + 10 when smaller; on SQLite `[storage.sqlite] pool_size` is raised to 2 \* (`max_concurrent_jobs` + 1), at most 34, when its snapshot slots (`pool_size / 2 - 1`, between 1 and 16) would refuse a job this knob admits. Memory: a running backup holds about 490 MiB (PostgreSQL) or 650 MiB (SQLite) at most in the pipeline's own terms for a table of items at the 32 MiB line cap, a few tens of MiB for 200-byte items (the figures are for the default `max_item_size_bytes`, 400 KB, where no stored item's line exceeds the cap; on an instance that raises it the terms are at the largest line a stored item expands to, about 68 times the item's size for the worst shape); with glibc's default allocator the process's high-water mark grows with the number of large items a job reads (measured 760 MiB over idle at 48 items of 27.7 MB on a quiet host and 1,281 MiB on a loaded one, 1.39 and 2.35 times the terms at that item size) because the items' strings are allocated on one thread and freed on another and the per-thread arenas keep that memory. Set `MALLOC_ARENA_MAX=1` in the server's environment (the deployment guide's service unit carries the line, commented out) on a host that backs up large items: the peak is then the terms' and does not grow with the table (measured 452 to 481 MiB over idle at 12, 24 and 48 items of 27.7 MB on SQLite, in two series on two hosts' loads, and 340 MiB `VmHWM` (about 200 MiB over idle) at 12 items on PostgreSQL); one arena serializes the worker threads' allocations on one lock and costs the request path a few percent (measured 3.5 to 9.2% on GetItem, Query and Scan on SQLite and about 2% on PostgreSQL (the scans, 2.1%), where the request path waits on the database on PostgreSQL). Size the host for 1.2 times the terms (about 590 MiB on PostgreSQL, 780 MiB on SQLite) times this knob under `MALLOC_ARENA_MAX=1`; without it the peak grows with the large rows a job reads and no bound was measured (1,281 MiB over idle at 48 items of 27.7 MB is the largest seen). A running restore holds the parsed manifest, one decoded data-file line and its parse, the decoded items of 32 MiB of data-file text plus one line per chunk (the chunk closes with the item that reaches the bound) at four chunk positions between the decoder and the load (two in the channel, the one being filled, the one being drained; a chunk also closes at 1,000 items, and the chunks never hold more than one data file's items), and the backend's write batch: at most 32 MiB of item text on SQLite and Cassandra (10,000 items when they are smaller), held beside the decoded items of that text; 500 items (or 4 MiB) per INSERT statement inside one transaction per data file on PostgreSQL; 1,000 documents per `insert_many` on MongoDB (the driver splits the call); times this knob. For a table of large items that is the same order as the backup, not less: measured `VmHWM` over idle from a fresh start (`docs/design/15-backup-restore-bench-pr9.md`), 24 items of 27.7 MB restore with a peak of 848 MiB on SQLite and 778 MiB on PostgreSQL under the default allocator (848 and 1,013 MiB at 12 and 48 such items on SQLite: the peak grows with the large items a restore reads, as the backup's does, and no bound was measured), and 392 MiB on SQLite and 427 MiB on PostgreSQL under `MALLOC_ARENA_MAX=1`, the same setting as above; 1,200 items of 350 KB in one data file 270 MiB on SQLite and 156 MiB on PostgreSQL; 1M items of 200 bytes under a composite key with no secondary index, the backup's lines in key order as the server's own backups are, 89 MiB on SQLite (the write connection's page cache and the final `COUNT(*)`, each bounded by `cache_size`; the count's share was 22 to 28 MiB at 1M and at 3M rows) and 16 MiB on PostgreSQL, and the same 1M items as an unordered backup (every MongoDB-sourced backup and every multi-part-key table) 144 to 164 MiB on SQLite in 66 to 90 s against 27 to 56 s key-ordered (scattered inserts dirty the whole base b-tree; the restore's buffers are the same) and 16 MiB on PostgreSQL; the same items under the same key with two full-projection GSIs 143 to 225 MiB on SQLite at 100,000 items in three runs and 165 to 172 MiB at 300,000, and 23 to 34 MiB on PostgreSQL at both: the excess on SQLite is the backend's own per-connection page cache (`cache_size`, 32 MiB) holding the index tables' b-tree pages plus the allocator's arenas (about a third less under `MALLOC_ARENA_MAX=1`), not the restore's buffers, which the 32 MiB batch bound holds whatever the indexes; it is bounded by `cache_size` and grows sub-linearly with the table. Size the host for about 450 MiB per running restore of large items under `MALLOC_ARENA_MAX=1`, times this knob, plus about 32 MiB of page cache per running restore of an indexed table on SQLite, and read the 1M figure for 200-byte items as the key-ordered shape's: an unordered backup of them restores in about 1.5 to 1.8 times that on SQLite. The page-cache term is for B-tree indexes. On SQLite a restore of items of more than a few hundred bytes, of any attribute types, holds more: its write batch (up to 10,000 items or 32 MiB of item text) and the decode chunks in front of it grow with the item's size up to that bound, and lists of numbers decode larger than strings of the same size; the [Backup and Restore manual](./manuals/14-backup-and-restore.md#memory-while-a-job-runs) has the measured points. | +| `spool_path` | none | Restore download area for an S3 backup store, created 0700 with files 0600 and holding a `.lock` another instance on the host refuses. A store-backed restore from an S3 store downloads each data file here under `restore-
/` (`.json.gz`, `` zero-padded to six digits, with a `.verified` marker holding the file's sha256, written only after the file's digests matched and trusted only while it names the digest the manifest records, plus the manifest and sidecar), reads it from there, and removes the entry when the restore ends, except when it ended because the record had become another instance's (its claim lost, a status write that matched no record), where the sweep removes it; an entry left by an earlier run of this host for a record another host then owned is removed before a new run of the same restore uses it; the reconciler sweeps the `restore-` entry of a restore no longer RUNNING with this host's `spool_host`. Its disk cost is the compressed backup of the restore in flight. A filesystem store needs no spool (files are hashed in place and read again). Required with an S3 store, except on file-backed SQLite where it defaults to `backup-spool/` beside the database file. Refused inside or containing a filesystem store root, and when it is or contains the database file's directory. Example: `spool_path = "/var/lib/extenddb/spool"` | + +## `[backup.store]` + +Where CreateBackup writes its backups on PostgreSQL, SQLite and MongoDB (CreateBackup answers CREATING and a job of the server uploads; Cassandra writes in-catalog backups with or without a store), and where restores and deletes of store-backed backups read. The section's keys, defaults and the refusals of a bad value are the backup store crate's (`crates/backup-store/src/config.rs`). Absent on file-backed SQLite: a filesystem store at `backups/` beside the database file. Absent on PostgreSQL, MongoDB, Cassandra and an in-memory SQLite database: no store, and CreateBackup writes in-catalog backups with a deprecation warning. Instances that share a catalog must share one store root (an S3 bucket and prefix, or a shared mount). The administration guide's section on the backup store covers startup validation, the store identity file and the `extenddb backup` commands. + +| Key | Default | Description | +|-----|---------|-------------| +| `kind` | `"filesystem"` | Which store the section selects: "filesystem", "s3" or "disabled". "disabled" opts out of the per-backend default on any backend. | + +## `[backup.store.filesystem]` + +Read when `kind = "filesystem"`. + +| Key | Default | Description | +|-----|---------|-------------| +| `path` | none | Root directory for backup objects. It must exist, be owned by the extenddb user with mode 0700, and sit under directories owned by root or by that user which others cannot write to; the server refuses anything else at startup. A relative path, like a relative `spool_path`, is resolved against the working directory the server was started from (the daemon's own working directory is `/`). Example: `path = "/var/lib/extenddb/backups"` | + +## `[backup.store.s3]` + +Read when `kind = "s3"`. Credentials are not in the file: they come from the AWS SDK's credential chain. + +| Key | Default | Description | +|-----|---------|-------------| +| `bucket` | none | Destination bucket. Example: `bucket = "my-extenddb-backups"` | +| `prefix` | `""` | Key prefix inside the bucket; empty means the bucket root. | +| `region` | none | Region override. When absent the SDK chain resolves the region, querying the instance metadata service when the environment and the profile name none. Example: `region = "us-east-1"` | +| `endpoint` | none | Endpoint override for an S3-compatible store. Example: `endpoint = "http://127.0.0.1:9000"` | +| `allow_insecure_endpoint` | `false` | Accept an `http://` endpoint whose host is not a loopback address, or an S3 endpoint without `force_path_style`, for the S3 client, the credential providers' clients and the instance metadata client alike. Off by default: such an endpoint can carry requests, credentials and objects in clear text across the network. | +| `force_path_style` | `false` | Use path-style addressing; required by most S3-compatible stores, and by an `http://` endpoint unless `allow_insecure_endpoint` is set. | +| `upload_part_size_bytes` | `8388608` | Multipart part size in bytes (8 MiB). The enforced range is 5 MiB to 5 GiB, the smallest and largest part S3 accepts. Each part must upload within the 60 s attempt timeout, so keep it at most about the link's bytes per second times 60. | +| `max_concurrent_uploads` | `4` | Maximum concurrently in-flight part uploads per put. | + +## `[import]` + +Import and export file operations are disabled until a directory is listed here. Every file path is canonicalized and must resolve under one of the configured roots; a symlink that escapes a root is rejected. Files are namespaced per account beneath each root: a caller in account 111122223333 may only read under <root>/111122223333, and a path that resolves elsewhere is rejected, so tenants sharing an instance cannot read each other's files. + +On Unix, export files are created with mode 0600, and the directories the server creates to hold import and export files are created with mode 0700: a missing import or export root, created at startup, and the account directory an export creates under each export root. Missing parent directories of a root are created 0755. A directory that already exists keeps its mode. The umask can only narrow these modes. At startup the server warns about a root with a parent directory that group or others can write to without the sticky bit, since another user could replace the root through it. + +| Key | Default | Description | +|-----|---------|-------------| +| `paths` | `[]` | Directories imports may read from, for example /var/lib/extenddb/imports. Empty means imports are denied. | + +## `[export]` + +Same rules as [import]. Export refuses to overwrite an existing file. + +| Key | Default | Description | +|-----|---------|-------------| +| `paths` | `[]` | Directories exports may write to, for example /var/lib/extenddb/exports. Empty means exports are denied. | diff --git a/docs/install-from-source.md b/docs/install-from-source.md index eb9b86a3d..7e77fcc63 100644 --- a/docs/install-from-source.md +++ b/docs/install-from-source.md @@ -561,7 +561,7 @@ Stop the server, then drop the databases. ./target/release/extenddb destroy --config extenddb.toml --yes --pg-user postgres ``` -On PostgreSQL, `destroy` connects as the same administrator `init` used: pass the same `--pg-user`, with `EXTENDDB_PG_PASSWORD` set, and omit `--pg-user` where PostgreSQL runs as your own user. It drops both databases; the `extenddb` application role, `extenddb.toml` and the certificate under `~/.extenddb/tls/` are left in place and a later `init` reuses them. On MongoDB it drops the two databases through the configured connection string. On SQLite it removes the database file and its `-wal` and `-shm` files. It leaves the `.lock` file and the default backup store directory `backups/` beside them. Remove `backups/` too before a new `init`; otherwise the new server reports that store as owned by another catalog (see [`[backup.store]`](manuals/05-admin-guide.md#backupstore) in the administration guide). `--yes` is required; there is no interactive prompt. +On PostgreSQL, `destroy` connects as the same administrator `init` used: pass the same `--pg-user`, with `EXTENDDB_PG_PASSWORD` set, and omit `--pg-user` where PostgreSQL runs as your own user. It drops both databases; the `extenddb` application role, `extenddb.toml` and the certificate under `~/.extenddb/tls/` are left in place and a later `init` reuses them. On MongoDB it drops the two databases through the configured connection string. On SQLite it removes the database file and its `-wal` and `-shm` files. It leaves the `.lock` file and the default backup store directory `backups/` beside them. Remove `backups/` too before a new `init`; otherwise the new server reports that store as owned by another catalog (see the [backup store section](manuals/05-admin-guide.md#backup-store-and-the-extenddb-backup-commands) of the administration guide). `--yes` is required; there is no interactive prompt. Stop the database you started in step 1: `docker stop extenddb-mongo extenddb-cassandra` for the containers, `brew services stop postgresql@17` or `brew services stop mongodb-community@7.0` on macOS, `sudo systemctl stop postgresql` or `sudo systemctl stop mongod` on Linux. diff --git a/docs/manuals/05-admin-guide.md b/docs/manuals/05-admin-guide.md index 978826f61..cb7025615 100755 --- a/docs/manuals/05-admin-guide.md +++ b/docs/manuals/05-admin-guide.md @@ -114,69 +114,21 @@ for backend failures. ### extenddb.toml: Static Configuration -These settings require a server restart to take effect. +Every key of `extenddb.toml`, its default and what it controls is listed on the [Configuration](../configuration.md) page, which is generated from `extenddb.sample.toml` and checked against the configuration structs by the test suite. These settings take effect at the next server start. Scalar keys can also be set through an environment variable with the `EXTENDDB__` prefix and `__` between levels (`EXTENDDB__SERVER__PORT=9000`); the list keys (`import.paths`, `export.paths`, `storage.cassandra.contact_points`) and the numeric keys of `[storage.sqlite]` and `[storage.cassandra]` are file only. Precedence, highest first, is environment variables, the configuration file, then the built-in defaults; `extenddb serve --port` overrides `server.port` on top of all three. -#### [server] +#### PostgreSQL connection budget and restores -| Key | Default | Description | -|-----|---------|-------------| -| `bind_addr` | `127.0.0.1` | Network interface to bind | -| `port` | `18443` | HTTP port | -| `region` | `us-east-1` | AWS region for ARN generation. Requests must carry a credential scope for this region; any other region is rejected with `InvalidSignatureException`, as the service rejects a scope for a region other than the endpoint's. Baked into every backup ARN the server issues, so it must stay within `[a-z0-9-]` (under a value outside that class `CreateBackup` is refused with a `ValidationException` naming `server.region`, since no backup ARN can be formed; backups taken before the upgrade under such a region keep an ARN `DescribeBackup`, `DeleteBackup`, and `RestoreTableFromBackup` refuse as "not valid"; the server logs a warning at startup). A backup ARN of the caller's account in another region is resolved in the server's region first, then as written; see the upgrade manual before changing this on a deployment with backups | -| `request_timeout_secs` | `30` | Seconds a connection may take to deliver its request headers, and seconds a request body may stall without delivering data, before the server closes it (a stalled body gets HTTP 408). A connection that is accepted, or that completes the TLS handshake, and then sends no byte is closed after the same number of seconds, as is one that sends only part of the 24-byte HTTP/2 preface. The same value bounds how long an idle keep-alive connection waits for its next request, so SDK connection pools see idle connections closed after it (they reopen transparently), and it is the HTTP/2 keep-alive PING interval and timeout, so a stalled HTTP/2 connection is closed within twice the value. Must be at least 1 and at most 86400 (a day); the server refuses a larger value at startup, because the per-connection timers add it to the current instant and a value near `u64::MAX` overflows that addition | +The `pool_size` key of `[storage.postgres]` sizes two pools, one against the catalog database and one against the data database; the Configuration page gives the connection arithmetic. Restores draw on the same pool. -#### [storage] - -| Key | Default | Description | -|-----|---------|-------------| -| `backend` | `postgres` | Storage backend: `postgres`, `mongodb`, `sqlite` or `cassandra`. Must match the feature the binary was built with; see [Storage backends](../storage-backends.md) | - -ExtendDB owns the collections, tables and indexes of its catalog and data databases. A change to them, such as an added index, is not supported and can make a later migration fail. - -#### [storage.postgres] - -| Key | Default | Description | -|-----|---------|-------------| -| `connection_string` | `postgresql://extenddb:extenddb-local-dev@localhost:5432/extenddb_catalog` | Catalog database connection string | -| `pool_size` | `20` | Maximum concurrent database connections (minimum: 10) | -| `catalog_pool_size` | (= `pool_size`) | Maximum connections for management/authz pool (minimum: 10) | - -Backup and restore jobs are bounded per server process by `[backup] max_concurrent_jobs` (default 4, below), not per account; a request that finds every slot held waits up to 30 s for one and is then refused with `LimitExceededException`. The server raises `pool_size` and `catalog_pool_size` to at least `2 * max_concurrent_jobs + 10` and logs the raise with both numbers, so every job the bound admits has a connection. Each running restore holds one connection from this pool for its whole copy, plus one dedicated connection outside the pool for its claim. +Backup and restore jobs are bounded per server process by `[backup] max_concurrent_jobs` (default 4, on the [Configuration](../configuration.md) page), not per account; a request that finds every slot held waits up to 30 s for one and is then refused with `LimitExceededException`. The server raises `pool_size` and `catalog_pool_size` to at least `2 * max_concurrent_jobs + 10` and logs the raise with both numbers, so every job the bound admits has a connection. Each running restore holds one connection from this pool for its whole copy, plus one dedicated connection outside the pool for its claim. `RestoreTableFromBackup` on PostgreSQL holds a session-level advisory lock (the job's claim) for the whole copy, so ExtendDB must reach the catalog database directly or through a session-mode pooler. Behind a transaction-mode pooler (for example PgBouncer with `pool_mode = transaction`) the lock lands on a pooled server connection and is not released with the job, so later jobs can be refused as already claimed; do not run backups or restores through one. -#### [storage.sqlite] - -| Key | Default | Description | -|-----|---------|-------------| -| `path` | `extenddb.sqlite` | Database file (`init --sqlite-path` writes it); `:memory:` for an ephemeral database, whose catalog is new at every start: with `[backup.store]` configured the server adopts the root an earlier in-memory catalog owned and syncs its backups into the new catalog before it serves, within 60 s (an S3 store in the reconciler's first cycle; a sync not finished in 60 s, or one that met a store or catalog error on a prefix, runs again in the next cycle). Every run lists the root from its first key, so the startup sync completes only while listing the whole root fits in 60 s; past that it stays pending, is retried every cycle, and the backups beyond what a run reaches are not served. A run holds the whole listing of the root in memory (one entry per object) until it ends, and a listing that outlasts 60 s reaches no prefix. On a filesystem store a run abandoned at the 60 s bound does not stop its listing: the walk of the root runs to its end on the blocking pool, holding the listing it builds, and no second walk starts beside it; until it ends, every check of the store is refused at once ("an abandoned startup sync's store call has not returned") and records the store `unreachable`, so CreateBackup, DeleteBackup and restores are refused and the sync does not run; the first reconciler cycle after the walk ends finds the store healthy and runs the sync again, from the first key. A root too large to list within 60 s is never synced by an in-memory server: give it a smaller root, or a durable catalog. On a filesystem store the server does not answer, `/health` included, until the startup sync ends (a liveness probe with a short timeout restarts such a server on a large root, each start syncing from the first key), and a signal then ends the process at once. Until the log line `startup sync of the in-memory catalog: N backup(s) adopted` the earlier backups answer `BackupNotFoundException`, although `/health` may already report the store healthy; a prefix that line reports as having met a store or catalog error stays so until a later cycle's line. Each run names the prefixes it skipped for a store or catalog error at WARN; until one run has listed the whole root and logged its line of counts, each run also names every other prefix it skipped at INFO (so the reasons reach the log when the first run was cut at the bound or stopped by an error), and a later run of a sync left pending logs those at DEBUG, so a root of many backups with one that fails costs one WARN line and the line of counts per cycle. A server killed inside a DeleteBackup (between the DELETING write and the manifest's deletion), or restarted after a DeleteBackup whose manifest deletion failed, serves that backup again at its next start, since the startup sync adopts the complete prefix; a prefix a stopped server had not finished writing or deleting (a killed CreateBackup, a failed backup whose prefix deletion had not finished, a deletion cut after its manifest) stays under the root with no row to drive its deletion (the next start's sync skips a prefix without its manifest); the startup sync names each such prefix in its log line `backup store startup sync: not adopted: not a complete backup: ...`. Delete such a prefix by hand, since every `extenddb backup` command refuses an in-memory database, but only one that has no `extenddb-manifest.json` and whose backup `ListBackups` does not return: a CreateBackup the running server is still writing has no manifest until its last put either, and its row is in `ListBackups` (status CREATING). Start a new in-memory server only after the old one has exited: one started beside it adopts the root while the old one still acts on it until a later check finds it adopted, its deletion fence (the identity paragraph) excepted. A root that an in-memory server of an earlier development build wrote has an `extenddb-store.json` without `ephemeral_catalog` (no release wrote one), which reads as a durable catalog's: the server finds the root owned by another catalog, its store stays unhealthy, and no command can adopt it. Remove that `extenddb-store.json`; the next start writes a new one (a new store id) and adopts the backups under the root. Every `extenddb backup` command refuses it | -| `pool_size` | `10` | Maximum connections. Writes are serialized by the engine whatever the size. A file database raises `pool_size = 1` to 2 and logs it at info (`SQLite pool_size 1 raised to 2 for a file-backed database: ...`), because a backup holds one reader connection for its whole duration while its batches write through another. Use 3 or more so a running backup does not contend with ordinary requests for connections | - -#### [backup] - -The knobs backup and restore jobs and the reconciler read; every key has a default, and the section may be left out. This section and `[backup.store]` below are the reference for the keys and the `extenddb backup` commands; the [Backup and Restore manual](14-backup-and-restore.md) covers the strategy, the recovery point and time, securing the store, the restore drill and catalog-loss recovery. +#### Backup store and the extenddb backup commands -| Key | Default | Description | -|-----|---------|-------------| -| `data_file_target_bytes` | `67108864` | Uncompressed bytes per backup data file (minimum 32 MiB, the cap on one line): a data file closes at the first item that takes it to or past this, so it exceeds it by less than one line | -| `heartbeat_interval_secs` | `15` | The job heartbeat timer. The store-backed backup job heartbeats every `max(heartbeat_interval_secs, 15)` s and starts no store write unless a beat confirmed its claim within two periods or a beat is still in flight (on SQLite a beat waits behind any writer holding the engine write lock, a GSI backfill say, for as long as it holds it, and a backup goes on writing meanwhile; on the other backends a beat in flight does not count), the claim's insert counting as the first beat; the in-catalog backup and restore paths heartbeat every 15 s whatever this says | -| `stale_job_after_secs` | `300` | Heartbeat age after which a job's owner is dead (on PostgreSQL, once the owner's claim session has ended as well) and the reconciler resolves the job, and after which a maintenance command that died (killed, or its catalog connection lost) no longer holds the maintenance claim, on PostgreSQL too (until then the next one fails at once, naming the holder): a dead backup job with a complete manifest under its prefix is AVAILABLE, one without is FAILED and its prefix deleted; a dead in-catalog restore job is FAILED and its target removed; a dead store-backed restore is resumed from its recorded progress (the differences document's restore-interruption row). Must be at least three heartbeat periods, where the period is the larger of `heartbeat_interval_secs` and the 15 s the in-catalog jobs heartbeat at (so 45 at the least, whatever `heartbeat_interval_secs` says); on SQLite a long write transaction delays a heartbeat, so keep a margin above that floor | -| `failed_row_retention_secs` | `604800` | How long FAILED and DELETED backup rows of the configured store are kept once their objects are gone (7 days); `extenddb backup list --failed` prints the FAILED ones with their reason. At least `stale_job_after_secs`: the reconciler deletes a stopped job's late object only under its row, so the row outlives the window in which that job can still write; a smaller value is refused at startup | -| `reconcile_interval_secs` | `60` | The reconciler's cycle; it also runs once at startup. Each cycle checks the store, resolves backup and restore jobs whose owner is dead, finishes deletions, deletes the objects of FAILED backups once their heartbeat is older than `stale_job_after_secs`, and removes tombstones past `failed_row_retention_secs` (the differences document's restore-interruption row lists the duties) | -| `max_concurrent_jobs` | `4` | Backup and restore jobs this instance runs at once (at most 1024); a request over it waits up to 30 s for a slot, then `LimitExceededException`. On PostgreSQL the pool sizes are raised to `2 * max_concurrent_jobs + 10` when smaller; on SQLite `[storage.sqlite] pool_size` is raised to `2 * (max_concurrent_jobs + 1)`, at most 34, when its snapshot slots (`pool_size / 2 - 1`, between 1 and 16) would refuse a job this knob admits. Memory: a running backup holds about 490 MiB (PostgreSQL) or 650 MiB (SQLite) at most in the pipeline's own terms for a table of items at the 32 MiB line cap, a few tens of MiB for 200-byte items (the figures are for the default `max_item_size_bytes`, 400 KB, where no stored item's line exceeds the cap; on an instance that raises it the terms are at the largest line a stored item expands to, about 68 times the item's size for the worst shape); with glibc's default allocator the process's high-water mark grows with the number of large items a job reads (measured 760 MiB over idle at 48 items of 27.7 MB on a quiet host and 1,281 MiB on a loaded one, 1.39 and 2.35 times the terms at that item size) because the items' strings are allocated on one thread and freed on another and the per-thread arenas keep that memory. Set `MALLOC_ARENA_MAX=1` in the server's environment (the deployment guide's service unit carries the line, commented out) on a host that backs up large items: the peak is then the terms' and does not grow with the table (measured 452 to 481 MiB over idle at 12, 24 and 48 items of 27.7 MB on SQLite, in two series on two hosts' loads, and 340 MiB `VmHWM` (about 200 MiB over idle) at 12 items on PostgreSQL); one arena serializes the worker threads' allocations on one lock and costs the request path a few percent (measured 3.5 to 9.2% on GetItem, Query and Scan on SQLite and about 2% on PostgreSQL (the scans, 2.1%), where the request path waits on the database on PostgreSQL). Size the host for 1.2 times the terms (about 590 MiB on PostgreSQL, 780 MiB on SQLite) times this knob under `MALLOC_ARENA_MAX=1`; without it the peak grows with the large rows a job reads and no bound was measured (1,281 MiB over idle at 48 items of 27.7 MB is the largest seen). A running restore holds the parsed manifest, one decoded data-file line and its parse, the decoded items of 32 MiB of data-file text plus one line per chunk (the chunk closes with the item that reaches the bound) at four chunk positions between the decoder and the load (two in the channel, the one being filled, the one being drained; a chunk also closes at 1,000 items, and the chunks never hold more than one data file's items), and the backend's write batch: at most 32 MiB of item text on SQLite and Cassandra (10,000 items when they are smaller), held beside the decoded items of that text; 500 items (or 4 MiB) per INSERT statement inside one transaction per data file on PostgreSQL; 1,000 documents per `insert_many` on MongoDB (the driver splits the call); times this knob. For a table of large items that is the same order as the backup, not less: measured `VmHWM` over idle from a fresh start (`docs/design/15-backup-restore-bench-pr9.md`), 24 items of 27.7 MB restore with a peak of 848 MiB on SQLite and 778 MiB on PostgreSQL under the default allocator (848 and 1,013 MiB at 12 and 48 such items on SQLite: the peak grows with the large items a restore reads, as the backup's does, and no bound was measured), and 392 MiB on SQLite and 427 MiB on PostgreSQL under `MALLOC_ARENA_MAX=1`, the same setting as above; 1,200 items of 350 KB in one data file 270 MiB on SQLite and 156 MiB on PostgreSQL; 1M items of 200 bytes under a composite key with no secondary index, the backup's lines in key order as the server's own backups are, 89 MiB on SQLite (the write connection's page cache and the final `COUNT(*)`, each bounded by `cache_size`; the count's share was 22 to 28 MiB at 1M and at 3M rows) and 16 MiB on PostgreSQL, and the same 1M items as an unordered backup (every MongoDB-sourced backup and every multi-part-key table) 144 to 164 MiB on SQLite in 66 to 90 s against 27 to 56 s key-ordered (scattered inserts dirty the whole base b-tree; the restore's buffers are the same) and 16 MiB on PostgreSQL; the same items under the same key with two full-projection GSIs 143 to 225 MiB on SQLite at 100,000 items in three runs and 165 to 172 MiB at 300,000, and 23 to 34 MiB on PostgreSQL at both: the excess on SQLite is the backend's own per-connection page cache (`cache_size`, 32 MiB) holding the index tables' b-tree pages plus the allocator's arenas (about a third less under `MALLOC_ARENA_MAX=1`), not the restore's buffers, which the 32 MiB batch bound holds whatever the indexes; it is bounded by `cache_size` and grows sub-linearly with the table. Size the host for about 450 MiB per running restore of large items under `MALLOC_ARENA_MAX=1`, times this knob, plus about 32 MiB of page cache per running restore of an indexed table on SQLite, and read the 1M figure for 200-byte items as the key-ordered shape's: an unordered backup of them restores in about 1.5 to 1.8 times that on SQLite. The page-cache term is for B-tree indexes. On SQLite a restore of items of more than a few hundred bytes, of any attribute types, holds more: its write batch (up to 10,000 items or 32 MiB of item text) and the decode chunks in front of it grow with the item's size up to that bound, and lists of numbers decode larger than strings of the same size; the [Backup and Restore manual](14-backup-and-restore.md#memory-while-a-job-runs) has the measured points | -| `spool_path` | (unset) | Restore download area for an S3 store, created `0700` with files `0600`, holding a `.lock` another instance on the host refuses. A store-backed restore from an S3 store downloads each data file here under `restore-
/` (`.json.gz`, `` zero-padded to six digits, with a `.verified` marker holding the file's sha256, written only after the file's digests matched and trusted only while it names the digest the manifest records, plus the manifest and sidecar), reads it from there, and removes the entry when the restore ends, except when it ended because the record had become another instance's (its claim lost, a status write that matched no record), where the sweep removes it; an entry left by an earlier run of this host for a record another host then owned is removed before a new run of the same restore uses it; the reconciler sweeps the `restore-` entry of a restore no longer RUNNING with this host's `spool_host`. Its disk cost is the compressed backup of the restore in flight. A filesystem store needs no spool (files are hashed in place and read again). Required with an S3 store, except on file-backed SQLite where it defaults to `backup-spool/` beside the database file. Refused inside or containing a filesystem store root, and when it is or contains the database file's directory | +The store CreateBackup writes to on PostgreSQL, SQLite and MongoDB, and the one restores and deletes of store-backed backups read. The section's keys, defaults and the refusals of a bad value are the backup store crate's (`crates/backup-store/src/config.rs`); the [Configuration](../configuration.md#backupstore) page lists the keys, and this section is what the server adds. One definition of the shape exists, so an unknown key anywhere under `[backup]` is refused at load. -#### [backup.store] - -The store CreateBackup writes to on PostgreSQL, SQLite and MongoDB, and the one restores and deletes of store-backed backups read. The section's keys, defaults and the refusals of a bad value are the backup store crate's (`crates/backup-store/src/config.rs`); the table below is what the server adds. One definition of the shape exists, so an unknown key anywhere under `[backup]` is refused at load. - -| Key | Default | Description | -|-----|---------|-------------| -| `kind` | see below | `filesystem`, `s3`, or `disabled` | -| `filesystem.path` | `backups/` beside a SQLite database file | The root directory of a filesystem store. It must exist, be owned by the extenddb user with mode `0700`, and sit under directories owned by root or that user which others cannot write to; `validate` refuses anything else at startup. A relative path, like a relative `spool_path`, is resolved against the working directory the server was started from (the daemon's own working directory is `/`) | -| `s3.bucket`, `s3.prefix`, `s3.region`, `s3.endpoint`, `s3.force_path_style`, `s3.allow_insecure_endpoint`, `s3.upload_part_size_bytes`, `s3.max_concurrent_uploads` | | The S3 store; see the crate's `config` module doc. Credentials come from the AWS SDK's chain and are never in the file | - -When the section is absent, the backend decides: on file-backed SQLite it is a filesystem store at `backups/` beside the database file, created `0700` if missing, whose validation or identity-check failure is a logged warning that leaves the store unconfigured rather than a startup error or an unhealthy store while the catalog has no backup rows for that root (so an upgrade never stops a server that never configured backups, and CreateBackup keeps working on one); once the catalog has rows for the default root, the root has been used and is handled as a configured one: a failure of its identity check or manifest probe is an unhealthy store (reported on `/health`, its rows' restores and deletes refused, `backup purge` refusing on it rather than reporting no store), and a refusal of its `open` or validation a startup error naming the root; on PostgreSQL, MongoDB, Cassandra and an in-memory SQLite database there is no default and the store is unconfigured, logged at startup. `kind = "disabled"` leaves it unconfigured on purpose on any backend. Without a configured store, CreateBackup writes the in-catalog backup format and logs a deprecation warning naming `[backup.store]` on each call. With one configured, CreateBackup on PostgreSQL, SQLite and MongoDB writes the backup to the store: the request takes the table's snapshot (after its checks and after any wait for a job permit, up to 30 s, so the backup is the table at that open and a write acknowledged during the wait is in it), writes the catalog row and answers `CREATING`, and a job of the server uploads gzip data files and the manifest under `/
//` below the root and marks the row `AVAILABLE` (the job's log lines carry the ARN: `backup : started, items in the table as last counted by the stats pass, key-ordered` (or `unordered`, for a table whose key shape or column collation has no format order) at the start, the stats pass's count, which is 0 on a table the pass has not reached, and `backup : AVAILABLE, items, bytes written in s` at the end, with the backup's own count); Cassandra, which has no table snapshot, keeps the in-catalog create with a store configured. Backups of either format stay listable, describable, deletable and restorable: a store-backed backup is restored by the restore job (the differences document's "How `RestoreTableFromBackup` runs" row; the `spool_path` row above and the `remove-target` command below are its operator surface), an in-catalog one by the previous path. +When the section is absent, the backend decides: on file-backed SQLite it is a filesystem store at `backups/` beside the database file, created `0700` if missing, whose validation or identity-check failure is a logged warning that leaves the store unconfigured rather than a startup error or an unhealthy store while the catalog has no backup rows for that root (so an upgrade never stops a server that never configured backups, and CreateBackup keeps working on one); once the catalog has rows for the default root, the root has been used and is handled as a configured one: a failure of its identity check or manifest probe is an unhealthy store (reported on `/health`, its rows' restores and deletes refused, `backup purge` refusing on it rather than reporting no store), and a refusal of its `open` or validation a startup error naming the root; on PostgreSQL, MongoDB, Cassandra and an in-memory SQLite database there is no default and the store is unconfigured, logged at startup. `kind = "disabled"` leaves it unconfigured on purpose on any backend. Without a configured store, CreateBackup writes the in-catalog backup format and logs a deprecation warning naming `[backup.store]` on each call. With one configured, CreateBackup on PostgreSQL, SQLite and MongoDB writes the backup to the store: the request takes the table's snapshot (after its checks and after any wait for a job permit, up to 30 s, so the backup is the table at that open and a write acknowledged during the wait is in it), writes the catalog row and answers `CREATING`, and a job of the server uploads gzip data files and the manifest under `/
//` below the root and marks the row `AVAILABLE` (the job's log lines carry the ARN: `backup : started, items in the table as last counted by the stats pass, key-ordered` (or `unordered`, for a table whose key shape or column collation has no format order) at the start, the stats pass's count, which is 0 on a table the pass has not reached, and `backup : AVAILABLE, items, bytes written in s` at the end, with the backup's own count); Cassandra, which has no table snapshot, keeps the in-catalog create with a store configured. Backups of either format stay listable, describable, deletable and restorable: a store-backed backup is restored by the restore job (the differences document's "How `RestoreTableFromBackup` runs" row; the `spool_path` key on the Configuration page and the `remove-target` command below are its operator surface), an in-catalog one by the previous path. Startup opens the configured store and, for a filesystem store, validates it and checks its identity before the listener is up (bounded by 5 s: a mount that stops answering after the root is opened leaves the server starting with the store `checking`; a root that does not answer at startup holds the server before the listener, as the database directory would, with the port bound and silent); an S3 store's validation and identity check are requests to the endpoint, and run after the listener is up, in the reconciler's first cycle, so an endpoint that stalls never holds the data plane down (the component is `checking` until the first result, and the operations that touch the store refuse meanwhile as they do while it is unhealthy). A configuration error, every one decided without a request to the store, stops startup with the key, path or bucket in the message: a root that does not exist or fails the owner-only rule, a filesystem root another user can reach, a filesystem root that is or contains the database directory, a bucket name the SDK routes to S3 Express, a bad part size or prefix, an insecure endpoint, an S3 store without `spool_path` on a backend with no default, a `spool_path` that breaks its placement rule, that another live instance holds or that exists with a mode other than `0700`. A transport failure (no region, no credentials, an endpoint that refuses connections or does not answer within the check's bound), a missing or denied bucket, an I/O failure of a filesystem root's probe write or resolution (a full or read-only disk, a stale network handle), or a failed identity check leaves the server running with the store unhealthy: the problem is logged once at error, `/health` reports the `backup_store` component unhealthy (status `degraded`), CreateBackup (where it writes to the store) and the restore and delete of a store-backed backup are refused with a `ValidationException` that names the store's kind and the problem's category and not its root, the reconciler acts on no row of the store, and the check runs again each `reconcile_interval_secs` until it passes, at which point the server logs `is healthy again` and resumes without a restart. Each check's store calls are bounded (5 s for a filesystem root, 30 s for a bucket); the catalog's own reads (the catalog id, the rows' store ids, the newest AVAILABLE row) run beside the calls and not under the bound, so a slow catalog costs the check time and never marks the store unhealthy. A store that has stopped answering costs a reconciler cycle that bound and nothing more, the cycle's other duties run as before, and the abandoned check is logged; on a filesystem root the abandoned check's call stays parked on one thread until the mount answers, no later cycle starts a check while it is (logged each cycle, the store staying `unreachable`), a root's calls run one at a time so that calls started before the first reached its bound (two `DeleteBackup` requests together, a `DeleteBackup` beside a check) wait for it under the bound, then have the bound for their own call (a slow call behind another finishes, where one bound over both would abandon it), and park no thread of their own, and `stop` or SIGTERM still ends the server, the runtime giving that thread 5 s before the process exits without it (after the job wait of up to 30 s when a backup job is running; see Stopping). The deletions `DeleteBackup` and the reconciler run against the store go through the same bound and rule: `DeleteBackup` answers the description with `BackupStatus` `DELETED` once its DELETING write has committed, and a deletion the store does not answer within the bound, or that leaves an object under the prefix, leaves the row DELETING for the reconciler and is logged, never an error to the client. A default SQLite root whose startup checks did not finish starts `checking` with its rule kept: a first check that fails while the catalog has no rows for it is the same warning and leaves the store unconfigured. CreateBackup on Cassandra is not refused by an unhealthy store: its in-catalog create touches no store. @@ -255,30 +207,8 @@ The maintenance claim is released. The third line's tail names the record's state: `was FAILED ()` or `was RUNNING with a dead owner`, after `its store-backed restore from ` or `its in-catalog restore from ` for the record's kind. A refusal is one `Error:` line on stderr (`
(account ) is not a restore target: no restore record names it`; `... its restore from is DONE (the table is ACTIVE, or awaits its index backfill)`; `the restore into
(account ) from is RUNNING with a live owner (a heartbeat within stale_job_after_secs); stop it or wait for it`; on PostgreSQL, `the restore into
(account ) from is a CREATING restore target (table id ) whose owner's lock is still held: its owner's session is alive though its heartbeat is stale; wait for the owner to stop, or stop it, and run the command again`, the owner's claim session holding the target's advisory lock, a frozen process for instance; `the maintenance claim is held by ""; one maintenance command runs at a time, and a claim whose holder died expires after stale_job_after_secs ( s)`). On SQLite it opens the database as `serve` does and takes the serve lock: stop the server first, as for `purge`; under that lock every owner is dead, so a `RUNNING` record's target is removed too. After it, `DescribeTable` of the name is `ResourceNotFoundException`, `DeleteBackup` of the backup succeeds and a new restore into the name runs. -#### [auth] - -| Key | Default | Description | -|-----|---------|-------------| -| `provider` | `builtin` | Auth provider: `builtin` (SigV4 + IAM). The server refuses to start with `"none"`. | - -#### [auth.encryption] - -| Key | Default | Description | -|-----|---------|-------------| -| `key_file` | unset | Path of the key-encryption key (KEK) file. Unset, the server encrypts stored secrets with the catalog key in the `encryption_key` row, as `extenddb init` created it. Set, it unwraps the data encryption key (DEK) from the `encryption_key_ring` row with the KEK in this file. Set it only after `extenddb encryption-key switch --yes` has run; the [Encryption Key](#encryption-key) section gives the procedure, the file format and the ownership and mode the file must have. A leading `~` expands as in the TLS key path, and the path must then be absolute: `serve` changes its working directory to `/` when it detaches, so the configuration refuses a relative path. An in-memory SQLite catalog refuses it. | -| `require_locked_memory` | `true` | With `key_file` set, the server refuses to start when it cannot lock the memory that holds the DEK and the cached signing keys, and names the memlock limit it needs. `false` turns that refusal into a warning. Without `key_file` the server warns and starts in either case. | - -#### [auth.cache] - -In-memory stale-while-revalidate caches eliminate the per-request catalog roundtrip for credentials, IAM policies, principal/resource tags, and table key info. Self-induced changes (admin API and console mutations) propagate instantly via write-through invalidation; off-instance changes take up to `ttl_seconds` to propagate. -| Key | Default | Description | -|-----|---------|-------------| -| `enabled` | `true` | Master kill switch. When `false`, all caches operate in pass-through mode. | -| `ttl_seconds` | `60` | Hard TTL: entries older than this trigger a fresh, request-blocking load. | -| `soft_ttl_seconds` | `30` | Stale-but-usable threshold; older entries still serve immediately while a background task refreshes them. | -| `negative_ttl_seconds` | `5` | Negative-cache TTL for "not found" results. | -| `max_entries` | `10000` | Maximum entries per cache. | +#### Auth cache statistics and invalidation timing Statistics are exposed at `/management/auth-cache-metrics` (JSON, admin-authenticated). The per-cache `pass_through` flag distinguishes "cache disabled" from "cache cold." The report includes every authorization sub-cache, among them the two principal creation-time caches (`user_created_at`, `role_created_at`) consulted on each user and role-session request to derive `aws:userid` and `aws:TokenIssueTime`. @@ -288,41 +218,6 @@ Statistics are exposed at `/management/auth-cache-metrics` (JSON, admin-authenti - **Fanout invalidations** (e.g. `DeleteAccount`, `DeleteRole` session sweep, `DeleteGroup` member fanout) also take effect when the API returns. The account and role sweeps register a predicate with moka, and moka's `get` applies it, so matching entries are not served once the call returns; moka removes them from its map during later cache operations. The group fanout drops each member's entries in turn. If a group change cannot list the group's members, the server logs a warning and those members' entries wait for `ttl_seconds`. - **Off-instance changes** (multi-node deployments, or direct catalog writes) wait up to `ttl_seconds` to be observed locally. -#### [server.tls] - -| Key | Default | Description | -|-----|---------|-------------| -| `enabled` | `true` | TLS is mandatory. The server refuses to start with `enabled = false`. | -| `cert_path` | `~/.extenddb/tls/cert.pem` | PEM certificate file | -| `key_path` | `~/.extenddb/tls/key.pem` | PEM private key file | - -`extenddb init` generates a self-signed certificate. Replace with a CA-signed certificate for production. - -#### [limits] - -All defaults match the DynamoDB service limits. Override only for testing edge cases. - -#### [logging] - -| Key | Default | Description | -|-----|---------|-------------| -| `level` | `info` | Initial log level (overridden by runtime setting) | -| `format` | `pretty` | Log format: `pretty` or `json` | - -The server logs to syslog (facility: daemon, ident: extenddb) when it runs as a daemon, and to stderr with `--foreground`. - -### Environment Variable Overrides - -Any config key can be overridden via environment variables using the `EXTENDDB__` prefix with `__` as separator: - -```bash -EXTENDDB__SERVER__PORT=9000 -EXTENDDB__STORAGE__POSTGRES__CONNECTION_STRING="postgresql://..." -EXTENDDB__AUTH__PROVIDER=builtin -``` - -Precedence: CLI flags > environment variables > config file > defaults. - ### Runtime Settings Managed via `extenddb settings set`. Changes take effect within 30 seconds without restart. A running server logs, under no audit target, when it applies a new `log_level`, `sqlx_log_level` or `throttling_enabled` value. diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index d384e47fc..0cad2bae6 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -34,7 +34,7 @@ An S3 store needs `spool_path` set on every backend except file-backed SQLite, w Migration 8 adds the `restore_progress` table to the PostgreSQL data database. Run `extenddb migrate --yes` before you start the new binary. If you restore the PostgreSQL data database from a dump taken before migration 8, run `extenddb migrate --yes` again. That dump has no data table for the target of a store-backed restore that was running. The reconciler marks such a restore `FAILED` and removes its target, so run the restore again. -If a store-backed restore whose server stopped has no recorded progress, the reconciler starts it again from its first data file. It marks the restore `FAILED` as `target_not_empty` only when the target holds more items than the backup. To restore that backup again, run `extenddb backup remove-target --account
`. It removes the target and its record (see the admin guide's [`[backup.store]`](05-admin-guide.md#backupstore) section). `backup remove-target` writes the catalog, so on SQLite stop the server for it, as for `purge`. +If a store-backed restore whose server stopped has no recorded progress, the reconciler starts it again from its first data file. It marks the restore `FAILED` as `target_not_empty` only when the target holds more items than the backup. To restore that backup again, run `extenddb backup remove-target --account
`. It removes the target and its record (see the admin guide's [backup store section](05-admin-guide.md#backup-store-and-the-extenddb-backup-commands)). `backup remove-target` writes the catalog, so on SQLite stop the server for it, as for `purge`. A rollback to 0.1.14 or an earlier release restores the catalog from the pre-upgrade backup (see [Migration 6](#migration-6-the-backup-catalog-index)), so a store-backed restore in flight loses its job record. A binary of those releases resumes no restore. Quiesce restores before a downgrade. diff --git a/docs/manuals/14-backup-and-restore.md b/docs/manuals/14-backup-and-restore.md index b89e7a5f7..3824bb833 100644 --- a/docs/manuals/14-backup-and-restore.md +++ b/docs/manuals/14-backup-and-restore.md @@ -186,9 +186,9 @@ size for the default-allocator figures, which these measurements do not bound. T ## Configuration The `[backup]` section's keys (the job bound, the heartbeat and reconciler intervals, `spool_path`) and the -`[backup.store]` section are documented in the admin guide's [`[backup]`](05-admin-guide.md#backup) and -[`[backup.store]`](05-admin-guide.md#backupstore) sections. The store's keys, defaults and refusals are the -backup store crate's, `crates/backup-store/src/config.rs`. +`[backup.store]` section are documented in the [`[backup]`](../configuration.md#backup) and +[`[backup.store]`](../configuration.md#backupstore) sections of the Configuration page. The store's keys, +defaults and refusals are the backup store crate's, `crates/backup-store/src/config.rs`. A filesystem store: @@ -274,8 +274,9 @@ the same copy rules before `backup sync` (the backups that the other directory's catalog's copy are in neither the restored catalog nor the kept directory, and the sync adopts only what the kept directory holds), and point every instance at the kept directory before the next backup. With an `extenddb-store.json` copied from one directory to the other nothing detects the split, and a restart can -delete the only copy of a backup (the admin guide's [`[backup.store]`](05-admin-guide.md#backupstore) -section). Point every instance at the shared root before the first backup, and never copy +delete the only copy of a backup (the admin guide's +[backup store section](05-admin-guide.md#backup-store-and-the-extenddb-backup-commands)). Point every +instance at the shared root before the first backup, and never copy `extenddb-store.json` between roots. `extenddb destroy` removes the databases and leaves the store: the store is the copy that survives it. diff --git a/extenddb.sample.toml b/extenddb.sample.toml index 9ad47326a..75ce4e40c 100755 --- a/extenddb.sample.toml +++ b/extenddb.sample.toml @@ -1,236 +1,750 @@ # Copyright 2026 ExtendDB contributors # SPDX-License-Identifier: Apache-2.0 -# extenddb configuration — sample template +# ExtendDB configuration: sample template # -# Copy this file to extenddb.toml and edit as needed. -# Or run `extenddb init` to generate one automatically. +# Copy this file to extenddb.toml and edit as needed, or run `extenddb init` +# to generate one. # # SECURITY: This file may contain the encryption key for credential storage. # Set permissions to 0600 (owner read/write only): chmod 600 extenddb.toml # The server refuses to start if permissions are more permissive. # -# All values shown are defaults. Uncomment and change to override. +# Every key the server reads appears below exactly once, commented out, with +# its default as the value. Uncomment a line and change the value to override +# the default. A key whose description says it has no default shows an example +# value instead. # -# Environment variable overrides use the EXTENDDB__ prefix with __ as separator: +# Environment variable overrides use the EXTENDDB__ prefix with __ as the +# separator between levels: # EXTENDDB__SERVER__PORT=9000 # EXTENDDB__STORAGE__POSTGRES__CONNECTION_STRING="postgresql://..." # EXTENDDB__AUTH__ENCRYPTION__KEY_FILE=/etc/extenddb/kek # EXTENDDB__AUTH__ENCRYPTION__REQUIRE_LOCKED_MEMORY=true +# Scalar keys accept this form. The list keys (import.paths, export.paths, +# storage.cassandra.contact_points) and the numeric keys of [storage.sqlite] +# and [storage.cassandra] are file only. +# Precedence: environment variables, then this file, then the built-in +# defaults. `extenddb serve --port` overrides server.port on top of all three. +# +# Runtime settings (log level, control plane delay, throttling at runtime) are +# changed with `extenddb settings set `, not in this file. The +# administration guide lists them under Runtime Settings. +# +# docs/configuration.md is generated from this file by +# `npm run gen:config` in website/; CI fails when the two differ. -# Path to the rendered documentation directory (HTML + PDF files). -# Generated by `python3 docs/build-docs.py`. When set, the web console -# serves documentation at /console/docs. When absent, the docs routes -# show a "not configured" message. -# `extenddb init` auto-discovers this directory if it exists. +# These keys sit at the top level and must appear before the first [section] +# header of the file. A top-level key placed after a header lands inside that +# section. Every section except [storage], [storage.cassandra] and the sections +# of the other backends then refuses to start the server with "unknown field" +# and the key named. [storage] reads only `backend` and the section of the +# binary's own backend, and drops any other key without an error. A binary does +# not read the sections of the other backends. [storage.cassandra] ignores a +# key it does not know. + +# Path to the rendered documentation directory (HTML and PDF files) produced +# by `python3 docs/build-docs.py`. When set, the web console serves the +# documentation at /console/docs; when absent, those routes show a "not +# configured" message. `extenddb init` discovers this directory when it +# exists. No default. # docs_dir = "/path/to/docs/rendered" +# Maximum import file size in bytes. When set, it replaces +# `limits.max_import_file_bytes`, which carries the 10 GB default. No default. +# max_import_bytes = 10737418240 + +# Deprecated: a single root for both import and export. It fills whichever of +# the [import] and [export] path lists is empty: with both lists filled it does +# nothing, with one filled it supplies the other, and with both empty (the +# sections as this file ships them) it makes the import and export roots the +# same directory. The server logs which of those happened at startup. Prefer +# the sections: this key will be removed. No default. +# import_export_root = "/var/lib/extenddb/data" + [server] -# bind_addr = "127.0.0.1" # Network interface to bind (default: localhost only) -# port = 18443 # HTTP port -# region = "us-east-1" # AWS region for ARN generation -# run_dir = "~/.extenddb/run" # Directory for PID file (~ is expanded to $HOME) +# The listening socket and the per-server behavior that is fixed at startup. +# The management web console is served at /console/ on the same address and +# port as the DynamoDB API and needs no configuration of its own. + +# Network interface to bind. The default listens on loopback only; bind +# 0.0.0.0 to accept connections from other hosts. A dev-mode build refuses a +# non-loopback address unless `EXTENDDB_DEV_ALLOW_ANY_BIND=1` is set in its +# environment, as the dev image sets it, because a container's published port +# decides exposure there. +# bind_addr = "127.0.0.1" + +# Listening port for the DynamoDB API, the management API and the console. +# port = 18443 + +# AWS region used when generating Amazon Resource Names (ARNs). Requests must +# carry a credential scope for this region; any other region is rejected with +# `InvalidSignatureException`, as the service rejects a scope for a region +# other than the endpoint's. Every backup ARN the server issues carries it, +# so the value must stay within [a-z0-9-]. Under a value outside that class +# the server logs a warning at startup and refuses `CreateBackup` with a +# `ValidationException` naming `server.region`, since no backup ARN can be +# formed; a backup taken earlier under such a region keeps an ARN that +# `DescribeBackup`, `DeleteBackup` and `RestoreTableFromBackup` refuse as not +# valid. A backup ARN of the caller's account in another region is resolved +# in the server's region first, then as written. See the +# [upgrade manual](./manuals/07-upgrade-manual.md) before changing it on a +# deployment that has backups. +# region = "us-east-1" + +# Directory for runtime files (the process ID file). A leading ~ expands to +# $HOME. When HOME is unset the default is /tmp. +# run_dir = "~/.extenddb/run" + +# Provisioned throughput throttling via in-memory token buckets. When true, +# tables with provisioned capacity are rate limited to their configured read +# capacity units (RCU) and write capacity units (WCU), on-demand tables use +# the default ceilings (12,000 RCU and 4,000 WCU), and the account-level +# aggregate limits in [limits] apply. This key sets the value the server +# starts with; once the `throttling_enabled` runtime setting has been written +# with `extenddb settings set`, the runtime setting takes precedence. Unset +# means throttling is off. No default. +# throttling_enabled = false + +# Seconds a connection may take to deliver its request headers, and seconds a +# request body may stall without delivering data, before the server closes the +# connection (a stalled body gets HTTP 408). Bounds how long a stalled or +# malicious client can hold a connection open. A connection that is accepted, +# or that completes the TLS handshake, and then sends no byte is closed after +# the same number of seconds, as is one that sends only part of the 24-byte +# HTTP/2 preface. The same value bounds how long an idle keep-alive connection +# waits for its next request, so SDK connection pools see idle connections +# closed after it (they reopen transparently), and it is the HTTP/2 keep-alive +# PING interval and timeout, so a stalled HTTP/2 connection is closed within +# twice the value. Must be at least 1 and at most 86400 (a day); the server +# refuses a larger value at startup, because the per-connection timers add it +# to the current instant and a value near `u64::MAX` overflows that addition. +# request_timeout_secs = 30 + +[server.tls] +# Transport Layer Security (TLS) is mandatory. `extenddb init` generates a +# self-signed certificate; replace it with one signed by a certificate +# authority for production use. + +# Accepted for backward compatibility. The server refuses to start when this +# is set to false. A dev-mode build serves plain HTTP on loopback and ignores +# this key. +# enabled = true + +# Path to the certificate file in Privacy Enhanced Mail (PEM) format. A +# leading ~ expands to $HOME. When HOME is unset the default is +# /tmp/extenddb-cert.pem. +# cert_path = "~/.extenddb/tls/cert.pem" + +# Path to the private key file in PEM format. A leading ~ expands to $HOME. +# When HOME is unset the default is /tmp/extenddb-key.pem. +# key_path = "~/.extenddb/tls/key.pem" [storage] -# backend = "postgres" # Storage backend: "postgres" (default), "mongodb", or "sqlite". - -# --- SQLite backend (developer mode) --- -# Select with `extenddb init --backend sqlite`. The database path can be given -# at init time (`extenddb init --sqlite-path `, written into this file) -# or set here. At serve time, the EXTENDDB__STORAGE__SQLITE__PATH environment -# variable overrides this value. -# Use ":memory:" for an ephemeral in-memory database (data lost on shutdown). -# [storage.sqlite] -# path = "extenddb.sqlite" +# Each ExtendDB binary contains exactly one storage backend and reads the +# [storage.] section with that backend's name. The other +# [storage.*] sections are ignored, so one file can carry all four. ExtendDB +# owns the collections, tables and indexes of its catalog and data databases. +# A change to them, such as an added index, is not supported and can make a +# later migration fail. + +# Name of the storage backend this file is written for: "postgres", +# "sqlite", "mongodb" or "cassandra". The key is optional; when present it +# is checked against the binary's compiled-in backend and the server refuses +# to start on a mismatch. No default. +# backend = "postgres" [storage.postgres] -# Connection string points to the CATALOG database. -# The catalog stores table metadata and the data database connection info. -# Multiple independent catalogs can coexist on one PostgreSQL instance. +# The connection string points to the catalog database, which stores table +# metadata and the connection information for the data database. Several +# independent catalogs can coexist on one PostgreSQL instance. +# +# Connection budget: `pool_size` sizes two pools, one against the catalog +# database and one against the data database, which `extenddb init` creates +# separately. Total PostgreSQL connections used: 2 * `pool_size` + +# `catalog_pool_size` + `[backup] max_concurrent_jobs` (one claim connection +# per running backup or restore job), plus one per vector index build running +# on this server and one while a schema migration runs. PostgreSQL's +# max_connections is per cluster, not per database, so both pools draw on the +# same budget. The defaults need 64 of PostgreSQL's default 100. The claim +# connections, the index build session and the migration connection sit +# outside every pool. A build's ownership lock is session scoped, so the build +# holds a session that ends with it; a pooled connection would return to the +# pool still holding the lock. A job's claim is a session-level advisory lock +# held the same way. The migration lock is transaction scoped and runs in one +# explicit transaction, so it needs a connection pinned to one PostgreSQL +# backend until COMMIT; a transaction-pooling proxy could otherwise move it +# between backends. The administration guide's section on the +# [connection budget and restores](./manuals/05-admin-guide.md#postgresql-connection-budget-and-restores) +# describes how backup and restore jobs draw on this pool. + +# Connection string for the catalog database. For production add +# `?sslmode=require` and a password of your own. # connection_string = "postgresql://extenddb:extenddb-local-dev@localhost:5432/extenddb_catalog" -# pool_size = 20 # Maximum concurrent database connections - # for DynamoDB data operations. Default: 20. - # Minimum: 10 (smaller values are clamped with - # a startup warning). This value sizes TWO - # pools: one against the catalog database and - # one against the data database, which `init` - # always creates separately. Total PostgreSQL - # connections used: 2 * pool_size + - # catalog_pool_size + [backup] max_concurrent_jobs - # (one claim connection per running backup or - # restore job), plus one per vector index - # build running on this server and one while a - # schema migration runs. max_connections is - # per cluster, not per database, so both pools - # draw on the same budget. The claim connections, - # the build session and the migration connection - # sit OUTSIDE every pool, for different reasons. - # A build's ownership lock is SESSION-scoped, so - # it needs a session that ends when the build - # ends: a pooled connection returns to the pool - # still holding the lock. The migration lock is - # TRANSACTION-scoped and needs a pinned - # connection instead, because its explicit - # transaction must retain one PostgreSQL backend - # until COMMIT; a transaction-pooling proxy could - # otherwise let the lock move between backends. - # Increase for higher concurrency; ensure - # PostgreSQL max_connections >= 2 * pool_size - # + catalog_pool_size + max_concurrent_jobs + - # the number of vector index builds you expect - # to overlap. The defaults already need 64 of - # PostgreSQL's default 100. -# catalog_pool_size = 20 # Maximum concurrent connections for the - # management/catalog pool (authz, IAM, console). - # Defaults to pool_size if not set. - # Minimum: 10 (smaller values are clamped with - # a startup warning). With auth enabled, each - # DynamoDB request makes concurrent authz queries - # — size this to match expected concurrency. + +# Maximum concurrent connections in each of the two data-operation pools. +# A value under 2 * `[backup] max_concurrent_jobs` + 10 (18 with the default +# of 4 jobs, 12 at the least) is raised to that at startup with a warning +# naming both numbers. Increase for higher concurrency and raise +# PostgreSQL's max_connections to at least 2 * `pool_size` + +# `catalog_pool_size` + `max_concurrent_jobs` + the number of vector index +# builds you expect to overlap. +# pool_size = 20 + +# Maximum connections for the management and catalog pool (authorization, +# Identity and Access Management (IAM), console). Raised to the same 2 * +# `max_concurrent_jobs` + 10 floor with a warning. With auth enabled each +# DynamoDB request makes concurrent authorization queries, so size this to +# match the expected request concurrency. Falls back to `pool_size` when +# absent. No default of its own. +# catalog_pool_size = 20 + +[storage.sqlite] +# Developer mode backend. Select it with `extenddb init --backend sqlite`. +# The database path can be given at init time (`extenddb init --sqlite-path +# `, written into this file) or set here; at serve time the +# `EXTENDDB__STORAGE__SQLITE__PATH` environment variable overrides it. + +# Database file. The default shown is the file build's. A `sqlite-memory` +# build defaults to ":memory:". A relative path is resolved against the working +# directory when the configuration loads, before `serve` daemonizes. ":memory:" +# selects an ephemeral in-memory database whose data is lost on shutdown and +# whose catalog is new at every start: with [backup.store] configured the server +# adopts the root an earlier in-memory catalog owned and syncs its backups +# into the new catalog before it serves, within 60 s (an S3 store in the +# reconciler's first cycle; a sync not finished in 60 s, or one that met a +# store or catalog error on a prefix, runs again in the next cycle). Every run +# lists the root from its first key, so the startup sync completes only while +# listing the whole root fits in 60 s; past that it stays pending, is retried +# every cycle, and the backups beyond what a run reaches are not served. A run +# holds the whole listing of the root in memory (one entry per object) until +# it ends, and a listing that outlasts 60 s reaches no prefix. On a filesystem +# store a run abandoned at the 60 s bound does not stop its listing: the walk +# of the root runs to its end on the blocking pool, holding the listing it +# builds, and no second walk starts beside it; until it ends, every check of +# the store is refused at once ("an abandoned startup sync's store call has +# not returned") and records the store `unreachable`, so CreateBackup, +# DeleteBackup and restores are refused and the sync does not run; the first +# reconciler cycle after the walk ends finds the store healthy and runs the +# sync again, from the first key. A root too large to list within 60 s is +# never synced by an in-memory server: give it a smaller root, or a durable +# catalog. On a filesystem store the server does not answer, `/health` +# included, until the startup sync ends (a liveness probe with a short timeout +# restarts such a server on a large root, each start syncing from the first +# key), and a signal then ends the process at once. Until the log line +# `startup sync of the in-memory catalog: N backup(s) adopted` the earlier +# backups answer `BackupNotFoundException`, although `/health` may already +# report the store healthy; a prefix that line reports as having met a store +# or catalog error stays so until a later cycle's line. Each run names the +# prefixes it skipped for a store or catalog error at WARN; until one run has +# listed the whole root and logged its line of counts, each run also names +# every other prefix it skipped at INFO (so the reasons reach the log when the +# first run was cut at the bound or stopped by an error), and a later run of a +# sync left pending logs those at DEBUG, so a root of many backups with one +# that fails costs one WARN line and the line of counts per cycle. A server +# killed inside a DeleteBackup (between the DELETING write and the manifest's +# deletion), or restarted after a DeleteBackup whose manifest deletion failed, +# serves that backup again at its next start, since the startup sync adopts +# the complete prefix; a prefix a stopped server had not finished writing or +# deleting (a killed CreateBackup, a failed backup whose prefix deletion had +# not finished, a deletion cut after its manifest) stays under the root with +# no row to drive its deletion (the next start's sync skips a prefix without +# its manifest); the startup sync names each such prefix in its log line +# `backup store startup sync: not adopted: not a complete backup: +# ...`. Delete such a prefix by hand, since every `extenddb backup` command +# refuses an in-memory database, but only one that has no +# `extenddb-manifest.json` and whose backup `ListBackups` does not return: a +# CreateBackup the running server is still writing has no manifest until its +# last put either, and its row is in `ListBackups` (status CREATING). Start a +# new in-memory server only after the old one has exited: one started beside +# it adopts the root while the old one still acts on it until a later check +# finds it adopted, its deletion fence (the store identity paragraph of the +# administration guide's backup store section) excepted. A root that an +# in-memory server of an earlier development build wrote has an +# `extenddb-store.json` without `ephemeral_catalog` (no release wrote one), +# which reads as a durable catalog's: the server finds the root owned by +# another catalog, its store stays unhealthy, and no command can adopt it. +# Remove that `extenddb-store.json`; the next start writes a new one (a new +# store id) and adopts the backups under the root. Every `extenddb backup` +# command refuses an in-memory database. +# path = "extenddb.sqlite" + +# Connection pool size. Writes are serialized by the engine whatever the +# size. A file database raises a value of 1 to 2 and logs it at info +# (`SQLite pool_size 1 raised to 2 for a file-backed database: ...`), because +# a backup holds one reader connection for its whole duration while its +# batches write through another; use 3 or more so a running backup does not +# contend with ordinary requests. Besides the `[backup] max_concurrent_jobs` +# bound, the process runs at most `pool_size` / 2 - 1 backups at once (between +# 1 and 16; 4 with the default) and refuses a CreateBackup that finds no slot +# free at once with LimitExceededException, without waiting; a file database +# raises a smaller `pool_size` to 2 * (`max_concurrent_jobs` + 1), at most 34, +# so that bound refuses no job `max_concurrent_jobs` admits. +# pool_size = 10 [storage.mongodb] -# MongoDB connection string. Requires a replica set (even single-node). +# MongoDB requires a replica set, even a single-node one, because conditional +# writes and transactions use multi-document transactions. + +# MongoDB connection string. Required. No default. # connection_string = "mongodb://localhost:27017/?replicaSet=rs0" -# max_connections = 50 # Maximum concurrent data-operation connections. -# max_catalog_connections = 20 # Shared catalog/auth pool for management and - # authorization traffic; size for their combined - # concurrency. + +# Maximum size of the data connection pool. Unset leaves the driver's pool +# size: the connection string's `maxPoolSize` when it has one, else the +# driver's default of 10 connections per server. The example is a production +# value. No default of its own. +# max_connections = 50 + +# Shared catalog and authorization pool for management and authorization +# traffic; size it for their combined concurrency. Unset leaves the driver's +# pool size, as for `max_connections`. The example is a production value. No +# default of its own. +# max_catalog_connections = 20 + +# Read concern for the multi-document transactions behind conditional writes, +# TransactWriteItems, TransactGetItems and idempotency tokens. Accepted +# values: "snapshot", "majority" and "local". "snapshot" keeps the single +# point-in-time guarantee. Some MongoDB-wire-compatible servers reject +# "snapshot" transactions with CommandNotSupported (code 115); set "majority" +# or "local" only when required. Both lose the point-in-time guarantee and +# "local" may read data that is later rolled back after a failover. The +# server logs a startup warning for either. # transaction_read_concern = "snapshot" - # Read concern for the multi-document transactions - # backing conditional writes, TransactWriteItems, - # TransactGetItems, and idempotency tokens. Accepted - # values: "snapshot", "majority", and "local". - # "snapshot" is the default, fidelity-preserving mode. - # Some MongoDB-wire-compatible backends (e.g. - # DocumentDB) reject "snapshot" transactions with - # CommandNotSupported (115); set this to "majority" - # or "local" only when required. Both lose the - # single point-in-time guarantee; "local" may read - # data later rolled back after failover. + +[storage.cassandra] +# Cassandra backend. Keyspaces are created with NetworkTopologyStrategy in the +# configured datacenter. One connection pool serves catalog and data traffic. + +# Contact points as host:port strings. Required. No default. +# contact_points = ["localhost:9042"] + +# Username for authentication. Omit for an unauthenticated cluster. No +# default. +# username = "cassandra" + +# Password for authentication. Omit for an unauthenticated cluster. No +# default. +# password = "cassandra" + +# Prefix of the keyspaces the backend creates. +# keyspace_prefix = "extenddb" + +# Replication factor for the keyspaces the backend creates. +# replication_factor = 3 + +# Datacenter name used in NetworkTopologyStrategy. +# datacenter = "datacenter1" + +# Maximum connections per host. +# max_connections = 10 [auth] -# provider = "builtin" # Auth provider: - # "builtin" — SigV4 verification with local credential - # store and IAM policy evaluation. - # Authentication is mandatory. The server refuses to start - # with provider = "none". Run `extenddb init` to create the - # encryption key and admin user before first start. +# Authentication is mandatory. Run `extenddb init` to create the encryption +# key and the admin user before the first start. + +# Auth provider. "builtin" verifies Signature Version 4 (SigV4) signatures +# against the local credential store and evaluates IAM policies. The server +# refuses to start with "none". +# provider = "builtin" [auth.cache] -# In-memory stale-while-revalidate caches sit between the request hot path -# and the catalog database. Each request would otherwise issue ~6 catalog -# queries during auth/authz; caching reduces this to ~0 in steady state. -# -# Self-induced changes (admin API mutations) propagate instantly via -# write-through invalidation. Off-instance changes (multi-node deployments -# or direct DB writes) take up to `ttl_seconds` to propagate. -# enabled = true # Master kill switch. When false, the - # cache wrappers bypass moka entirely - # (no lookup, no insert, no LRU pressure) - # and forward every request to the catalog. - # Use during incident response. -# ttl_seconds = 60 # Hard TTL — entries older than this trigger - # a fresh, request-blocking load. -# soft_ttl_seconds = 30 # Stale-but-usable threshold. Older entries - # are returned immediately while a background - # task refreshes them. Set equal to - # ttl_seconds to disable refresh-ahead. -# negative_ttl_seconds = 5 # Negative-cache TTL for "not found" results. - # Short by design so newly-created entities - # become usable quickly. -# max_entries = 10000 # Per-cache LRU cap. - -# The release before this one refuses an [auth.encryption] table, even an -# empty one, so the header stays commented until key_file is set. +# In-memory stale-while-revalidate caches sit between the request path and the +# catalog database. Without them each request issues about six catalog queries +# during authentication and authorization; with them the steady state is close +# to none. Changes made through this server's admin API propagate at once by +# write-through invalidation. Changes made elsewhere (other nodes of a +# multi-node deployment, or direct database writes) take up to `ttl_seconds` to +# become visible. The server refuses to start when `ttl_seconds` is 0, when +# `soft_ttl_seconds` or `negative_ttl_seconds` exceeds `ttl_seconds`, or when +# `max_entries` is 0. The administration guide's section on +# [cache statistics and invalidation timing](./manuals/05-admin-guide.md#auth-cache-statistics-and-invalidation-timing) +# covers the metrics endpoint. + +# Kill switch. When false, the cache wrappers skip lookup, insert and +# eviction and forward every request to the catalog. Use it during incident +# response. +# enabled = true + +# Hard time to live in seconds. Entries older than this trigger a fresh load +# that the request waits for. +# ttl_seconds = 60 + +# Stale-but-usable threshold in seconds. Entries older than this are returned +# at once while a background task refreshes them. Set it equal to +# `ttl_seconds` to disable refresh-ahead. +# soft_ttl_seconds = 30 + +# Time to live in seconds for negative results ("not found"). Short so newly +# created entities become usable quickly. +# negative_ttl_seconds = 5 + +# Maximum entries per cache; least recently used entries are evicted beyond +# it. +# max_entries = 10000 + # [auth.encryption] -# key_file = "/etc/extenddb/kek" # set after `extenddb encryption-key switch --yes`; unset keeps the catalog key -# require_locked_memory = true # with key_file set, refuse to start when the key store cannot be locked - -# Management web console is served at /console/ on the same port as the -# DynamoDB API. No separate configuration needed — it uses the same bind -# address and port as [server]. The console requires auth.provider = "builtin" -# (it authenticates against the admin_users and iam_users tables). - -# Provisioned throughput throttling via in-memory token buckets. -# When enabled, tables with provisioned capacity are rate-limited to their -# configured RCU/WCU. On-demand tables use default ceilings (12,000 RCU / -# 4,000 WCU). Account-level aggregate limits also apply. -# Disabled by default — enable for production-like behavior. -# throttling_enabled = false +# Where the key that encrypts stored secrets comes from. Without this section +# the server uses the catalog key in the `encryption_key` settings row, as +# `extenddb init` created it. The release before this one refuses an +# `[auth.encryption]` table, even an empty one, so the header stays commented +# until `key_file` is set. The administration guide's +# [Encryption Key](./manuals/05-admin-guide.md#encryption-key) section gives +# the procedure, the file format, the ownership and mode the file must have, +# and the delivery routes. -[server.tls] -# TLS is mandatory. The server refuses to start with enabled = false. -# cert_path = "~/.extenddb/tls/cert.pem" # PEM certificate file -# key_path = "~/.extenddb/tls/key.pem" # PEM private key file -# `extenddb init` generates a self-signed certificate automatically. -# Replace with a CA-signed certificate for production use. +# Path of the key-encryption key (KEK) file. When it is set, the server +# unwraps the data encryption key (DEK) from the `encryption_key_ring` +# settings row with the KEK in this file. Set it only after +# `extenddb encryption-key switch --yes` completes. A leading `~` expands as +# in the TLS key path. The configuration refuses a path that is relative +# after that expansion, because `serve` changes its working directory to `/` +# when it detaches. An in-memory SQLite catalog refuses this key. No default. +# key_file = "/etc/extenddb/kek" + +# With `key_file` set, refuse to start when the locked key store that holds +# the DEK and the cached signing keys cannot lock its memory. The refusal +# names the memlock limit it needs. false turns the refusal into a warning. +# Without `key_file` the server warns and starts in either case. +# require_locked_memory = true [limits] -# All defaults match real DynamoDB limits. -# Override only for testing edge cases. -# -# max_attribute_name_bytes = 65535 # REQ-LIM-004: 64 KB -# -# Preview extension: allow multi-part (composite) keys on base tables. -# GSIs always support multi-part keys regardless of this setting. +# The defaults match the DynamoDB service quotas. Override them only to test +# edge cases. + +# Maximum size of one item in bytes, attribute names and values included. +# max_item_size_bytes = 409600 + +# Maximum size of a partition key value in bytes. +# max_partition_key_size_bytes = 2048 + +# Maximum size of a sort key value in bytes. +# max_sort_key_size_bytes = 1024 + +# Shown on the console settings page. Not enforced: CreateTable does not +# count the account's tables. +# max_tables_per_account = 2500 + +# Maximum number of global secondary indexes per table. +# max_gsis_per_table = 20 + +# Maximum number of local secondary indexes per table. +# max_lsis_per_table = 5 + +# Largest Limit value ListTables accepts, and its page size when Limit is +# absent. +# list_tables_max_per_page = 100 + +# Maximum length of a table name in characters. +# max_table_name_length = 255 + +# Minimum length of a table name in characters. +# min_table_name_length = 3 + +# Value DescribeLimits reports as TableMaxReadCapacityUnits. CreateTable and +# UpdateTable do not enforce it. +# per_table_max_rcu = 40000 + +# Value DescribeLimits reports as TableMaxWriteCapacityUnits. CreateTable and +# UpdateTable do not enforce it. +# per_table_max_wcu = 40000 + +# Maximum aggregate read capacity units across the account, enforced when +# throttling is enabled and reported by DescribeLimits. +# per_account_max_rcu = 80000 + +# Maximum aggregate write capacity units across the account, enforced when +# throttling is enabled and reported by DescribeLimits. +# per_account_max_wcu = 80000 + +# Preview extension: allow multi-part (composite) keys on base tables. When +# false, base tables follow the DynamoDB rule of one HASH key and at most one +# RANGE key. Global secondary indexes allow multi-part keys regardless. # allow_multipart_table_keys = false +# Maximum attribute name size in bytes. +# max_attribute_name_bytes = 65535 + +# Maximum number of tokens in one expression (condition, update, projection +# or key condition). +# max_expression_tokens = 4096 + +# Maximum size of one expression string in bytes, measured on the text before +# #name and :value substitution. +# max_expression_length_bytes = 4096 + +# Maximum nesting depth of one expression. In a ConditionExpression or +# FilterExpression a parenthesized group, a NOT and a `size` operand each nest +# one level. AND and OR do not. In an UpdateExpression a parenthesized value +# and a function call each nest one level. +# max_expression_depth = 150 + +# Accepted but not read. The policy document size limit is fixed at 6,144 +# bytes, measured before JSON parsing. +# max_policy_document_bytes = 6144 + +# Maximum import file size in bytes (10 GB). The top-level `max_import_bytes` +# key replaces this value when set. +# max_import_file_bytes = 10737418240 + +# Maximum number of items in one import. +# max_import_item_count = 10000000 + +# Maximum number of items in one export. +# max_export_item_count = 10000000 + +# Reject bare reserved keywords in expressions, as the service does. +# enforce_reserved_keywords = true + [logging] -# level = "info" # Log level: trace, debug, info, warn, error -# format = "pretty" # Log format: "pretty" (human) or "json" (structured) -# -# Logging output is determined by the launch mode: -# extenddb serve → syslog (facility: daemon, ident: extenddb) -# Read logs with: journalctl -t extenddb -# No configuration needed — output always goes to syslog. - -# [backup] -# Backup and restore jobs and the reconciler. Every key has a default; the -# section may be left out. stale_job_after_secs must be at least three -# heartbeat periods, the larger of heartbeat_interval_secs and the 15 s the -# in-catalog jobs heartbeat at (45 at the least); max_concurrent_jobs is -# at most 1024; on PostgreSQL pool_size and catalog_pool_size are raised to -# at least 2 * max_concurrent_jobs + 10. -# data_file_target_bytes = 67108864 # Uncompressed bytes per data file (minimum 32 MiB) -# heartbeat_interval_secs = 15 # Job heartbeat timer -# stale_job_after_secs = 300 # Heartbeat age after which a job's owner is dead -# failed_row_retention_secs = 604800 # FAILED tombstones kept for the operator (7 days) -# reconcile_interval_secs = 60 # Reconciler cycle -# max_concurrent_jobs = 4 # Backup and restore jobs running at once on this instance -# spool_path = "/var/lib/extenddb/spool" # Restore download area for an S3 store; required -# # with an S3 store except on file-backed SQLite, where -# # it defaults to backup-spool/ beside the database file +# In daemon mode output goes to syslog (facility daemon, ident `extenddb`); +# read it with `journalctl -t extenddb`. With `extenddb serve --foreground` +# output goes to stderr for the process supervisor. The level set here is the +# one the server starts with; the `log_level` runtime setting changes it +# without a restart. + +# Log level: "trace", "debug", "info", "warn" or "error". +# level = "info" + +# Log format: "pretty" for humans or "json" for structured output. +# format = "pretty" + +[backup] +# The knobs backup and restore jobs and the reconciler read. Every key has a +# default, so the section may be left out. The server refuses to start when +# `stale_job_after_secs` is under three heartbeat periods, when +# `data_file_target_bytes` is under 32 MiB, when `max_concurrent_jobs` is 0 or +# over 1024, when `heartbeat_interval_secs` or `reconcile_interval_secs` is 0, +# or when `failed_row_retention_secs` is under `stale_job_after_secs`. This +# section and [backup.store] below are the reference for the keys; the [Backup +# and Restore manual](./manuals/14-backup-and-restore.md) covers the strategy, +# the recovery point and time, securing the store, the restore drill and +# catalog-loss recovery, and the administration guide's section on the backup +# store covers the `extenddb backup` commands. + +# Uncompressed bytes per backup data file, read by the store-backed backup +# writer. Minimum 33554432 (32 MiB), the cap on one line of a data file: a +# data file closes at the first item that takes it to or past this size, so +# it exceeds the size by less than one line. +# data_file_target_bytes = 67108864 + +# The job heartbeat timer, in seconds. The store-backed backup job heartbeats +# every max(`heartbeat_interval_secs`, 15) s and starts no store write unless +# a beat confirmed its claim within two periods or a beat is still in flight +# (on SQLite a beat waits behind any writer holding the engine write lock, a +# GSI backfill say, for as long as it holds it, and a backup goes on writing +# meanwhile; on the other backends a beat in flight does not count), the +# claim's insert counting as the first beat; the in-catalog backup and restore +# paths heartbeat every 15 s whatever this says. The staleness floor below is +# computed from the larger of the two. +# heartbeat_interval_secs = 15 + +# Heartbeat age in seconds after which a job's owner is dead (on PostgreSQL, +# once the owner's claim session has ended as well) and the reconciler +# resolves the job: a dead backup job with a complete manifest under its +# prefix is AVAILABLE, one without is FAILED and its prefix deleted; a dead +# in-catalog restore is FAILED and its target removed; a dead store-backed +# restore is resumed from its recorded progress (the differences document's +# restore-interruption row). After the same age a maintenance command that +# died (killed, or its catalog connection lost) no longer holds the +# maintenance claim, on PostgreSQL too (until then the next one fails at once, +# naming the holder). Must be at least three heartbeat periods, where the +# period is the larger of `heartbeat_interval_secs` and the 15 s the +# in-catalog jobs heartbeat at, so 45 at the least. On SQLite a heartbeat +# waits for the engine write lock like any writer, so a value near the floor +# can declare a live job dead on a busy file; keep a margin above the floor. +# stale_job_after_secs = 300 + +# How long FAILED and DELETED backup rows of the configured store are kept +# once their objects are gone, in seconds (7 days); `extenddb backup list +# --failed` prints the FAILED ones with their reason. At least +# `stale_job_after_secs`: the reconciler deletes a stopped job's late object +# only under its row, so the row outlives the window in which that job can +# still write; a smaller value is refused at startup. +# failed_row_retention_secs = 604800 + +# The reconciler's cycle, in seconds; it also runs once at startup. Each cycle +# checks the store, resolves backup and restore jobs whose owner is dead, +# finishes deletions, deletes the objects of FAILED backups once their +# heartbeat is older than `stale_job_after_secs`, and removes tombstones past +# `failed_row_retention_secs` (the differences document's restore-interruption +# row lists the duties). +# reconcile_interval_secs = 60 + +# Backup and restore jobs this instance runs at once, the in-catalog creates +# and restores included; at most 1024. A request that finds every slot held +# waits up to 30 s for one and is then refused with LimitExceededException. On +# PostgreSQL each running job holds one claim connection outside the pools, +# and `pool_size` and `catalog_pool_size` are raised to at least 2 * +# `max_concurrent_jobs` + 10 when smaller; on SQLite `[storage.sqlite] +# pool_size` is raised to 2 * (`max_concurrent_jobs` + 1), at most 34, when +# its snapshot slots (`pool_size / 2 - 1`, between 1 and 16) would refuse a +# job this knob admits. Memory: a running backup holds about 490 MiB +# (PostgreSQL) or 650 MiB (SQLite) at most in the pipeline's own terms for a +# table of items at the 32 MiB line cap, a few tens of MiB for 200-byte items +# (the figures are for the default `max_item_size_bytes`, 400 KB, where no +# stored item's line exceeds the cap; on an instance that raises it the terms +# are at the largest line a stored item expands to, about 68 times the item's +# size for the worst shape); with glibc's default allocator the process's +# high-water mark grows with the number of large items a job reads (measured +# 760 MiB over idle at 48 items of 27.7 MB on a quiet host and 1,281 MiB on a +# loaded one, 1.39 and 2.35 times the terms at that item size) because the +# items' strings are allocated on one thread and freed on another and the +# per-thread arenas keep that memory. Set `MALLOC_ARENA_MAX=1` in the server's +# environment (the deployment guide's service unit carries the line, commented +# out) on a host that backs up large items: the peak is then the terms' and +# does not grow with the table (measured 452 to 481 MiB over idle at 12, 24 +# and 48 items of 27.7 MB on SQLite, in two series on two hosts' loads, and +# 340 MiB `VmHWM` (about 200 MiB over idle) at 12 items on PostgreSQL); one +# arena serializes the worker threads' allocations on one lock and costs the +# request path a few percent (measured 3.5 to 9.2% on GetItem, Query and Scan +# on SQLite and about 2% on PostgreSQL (the scans, 2.1%), where the request +# path waits on the database on PostgreSQL). Size the host for 1.2 times the +# terms (about 590 MiB on PostgreSQL, 780 MiB on SQLite) times this knob under +# `MALLOC_ARENA_MAX=1`; without it the peak grows with the large rows a job +# reads and no bound was measured (1,281 MiB over idle at 48 items of 27.7 MB +# is the largest seen). A running restore holds the parsed manifest, one +# decoded data-file line and its parse, the decoded items of 32 MiB of +# data-file text plus one line per chunk (the chunk closes with the item that +# reaches the bound) at four chunk positions between the decoder and the load +# (two in the channel, the one being filled, the one being drained; a chunk +# also closes at 1,000 items, and the chunks never hold more than one data +# file's items), and the backend's write batch: at most 32 MiB of item text on +# SQLite and Cassandra (10,000 items when they are smaller), held beside the +# decoded items of that text; 500 items (or 4 MiB) per INSERT statement inside +# one transaction per data file on PostgreSQL; 1,000 documents per +# `insert_many` on MongoDB (the driver splits the call); times this knob. For +# a table of large items that is the same order as the backup, not less: +# measured `VmHWM` over idle from a fresh start +# (`docs/design/15-backup-restore-bench-pr9.md`), 24 items of 27.7 MB restore +# with a peak of 848 MiB on SQLite and 778 MiB on PostgreSQL under the default +# allocator (848 and 1,013 MiB at 12 and 48 such items on SQLite: the peak +# grows with the large items a restore reads, as the backup's does, and no +# bound was measured), and 392 MiB on SQLite and 427 MiB on PostgreSQL under +# `MALLOC_ARENA_MAX=1`, the same setting as above; 1,200 items of 350 KB in +# one data file 270 MiB on SQLite and 156 MiB on PostgreSQL; 1M items of 200 +# bytes under a composite key with no secondary index, the backup's lines in +# key order as the server's own backups are, 89 MiB on SQLite (the write +# connection's page cache and the final `COUNT(*)`, each bounded by +# `cache_size`; the count's share was 22 to 28 MiB at 1M and at 3M rows) and +# 16 MiB on PostgreSQL, and the same 1M items as an unordered backup (every +# MongoDB-sourced backup and every multi-part-key table) 144 to 164 MiB on +# SQLite in 66 to 90 s against 27 to 56 s key-ordered (scattered inserts dirty +# the whole base b-tree; the restore's buffers are the same) and 16 MiB on +# PostgreSQL; the same items under the same key with two full-projection GSIs +# 143 to 225 MiB on SQLite at 100,000 items in three runs and 165 to 172 MiB +# at 300,000, and 23 to 34 MiB on PostgreSQL at both: the excess on SQLite is +# the backend's own per-connection page cache (`cache_size`, 32 MiB) holding +# the index tables' b-tree pages plus the allocator's arenas (about a third +# less under `MALLOC_ARENA_MAX=1`), not the restore's buffers, which the 32 +# MiB batch bound holds whatever the indexes; it is bounded by `cache_size` +# and grows sub-linearly with the table. Size the host for about 450 MiB per +# running restore of large items under `MALLOC_ARENA_MAX=1`, times this knob, +# plus about 32 MiB of page cache per running restore of an indexed table on +# SQLite, and read the 1M figure for 200-byte items as the key-ordered +# shape's: an unordered backup of them restores in about 1.5 to 1.8 times that +# on SQLite. The page-cache term is for B-tree indexes. On SQLite a restore of +# items of more than a few hundred bytes, of any attribute types, holds more: +# its write batch (up to 10,000 items or 32 MiB of item text) and the decode +# chunks in front of it grow with the item's size up to that bound, and lists +# of numbers decode larger than strings of the same size; the [Backup and +# Restore manual](./manuals/14-backup-and-restore.md#memory-while-a-job-runs) +# has the measured points. +# max_concurrent_jobs = 4 + +# Restore download area for an S3 backup store, created 0700 with files 0600 +# and holding a `.lock` another instance on the host refuses. A store-backed +# restore from an S3 store downloads each data file here under `restore-
/` (`.json.gz`, `` zero-padded to six digits, with a `.verified` +# marker holding the file's sha256, written only after the file's digests +# matched and trusted only while it names the digest the manifest records, +# plus the manifest and sidecar), reads it from there, and removes the entry +# when the restore ends, except when it ended because the record had become +# another instance's (its claim lost, a status write that matched no record), +# where the sweep removes it; an entry left by an earlier run of this host for +# a record another host then owned is removed before a new run of the same +# restore uses it; the reconciler sweeps the `restore-` entry of a restore +# no longer RUNNING with this host's `spool_host`. Its disk cost is the +# compressed backup of the restore in flight. A filesystem store needs no +# spool (files are hashed in place and read again). Required with an S3 store, +# except on file-backed SQLite where it defaults to `backup-spool/` beside the +# database file. Refused inside or containing a filesystem store root, and +# when it is or contains the database file's directory. No default. +# spool_path = "/var/lib/extenddb/spool" # [backup.store] # Where CreateBackup writes its backups on PostgreSQL, SQLite and MongoDB # (CreateBackup answers CREATING and a job of the server uploads; Cassandra # writes in-catalog backups with or without a store), and where restores and -# deletes of store-backed backups read. Absent on file-backed SQLite: a filesystem -# store at backups/ beside the database file. Absent on PostgreSQL, MongoDB, -# Cassandra and an in-memory SQLite database: no store, and CreateBackup -# writes in-catalog backups with a deprecation warning. kind = "disabled" -# opts out on any backend. Instances that share a catalog must share one -# store root (an S3 bucket and prefix, or a shared mount). -# kind = "filesystem" # "filesystem" | "s3" | "disabled" +# deletes of store-backed backups read. The section's keys, defaults and the +# refusals of a bad value are the backup store crate's +# (`crates/backup-store/src/config.rs`). Absent on file-backed SQLite: a +# filesystem store at `backups/` beside the database file. Absent on +# PostgreSQL, MongoDB, Cassandra and an in-memory SQLite database: no store, +# and CreateBackup writes in-catalog backups with a deprecation warning. +# Instances that share a catalog must share one store root (an S3 bucket and +# prefix, or a shared mount). The administration guide's section on the +# backup store covers startup validation, the store identity file and the +# `extenddb backup` commands. + +# Which store the section selects: "filesystem", "s3" or "disabled". +# "disabled" opts out of the per-backend default on any backend. +# kind = "filesystem" + # [backup.store.filesystem] -# path = "/var/lib/extenddb/backups" # Must exist, owned by the extenddb user, mode 0700 +# Read when `kind = "filesystem"`. + +# Root directory for backup objects. It must exist, be owned by the extenddb +# user with mode 0700, and sit under directories owned by root or by that +# user which others cannot write to; the server refuses anything else at +# startup. A relative path, like a relative `spool_path`, is resolved against +# the working directory the server was started from (the daemon's own working +# directory is `/`). No default. +# path = "/var/lib/extenddb/backups" + # [backup.store.s3] +# Read when `kind = "s3"`. Credentials are not in the file: they come from the +# AWS SDK's credential chain. + +# Destination bucket. No default. # bucket = "my-extenddb-backups" -# prefix = "extenddb/" # Optional key prefix -# region = "us-east-1" # Optional; the AWS SDK's chain otherwise -# endpoint = "http://127.0.0.1:9000" # Optional, for an S3-compatible server -# force_path_style = true # Required with an http:// endpoint -# upload_part_size_bytes = 8388608 # 5 MiB to 5 GiB + +# Key prefix inside the bucket; empty means the bucket root. +# prefix = "" + +# Region override. When absent the SDK chain resolves the region, querying +# the instance metadata service when the environment and the profile name +# none. No default. +# region = "us-east-1" + +# Endpoint override for an S3-compatible store. No default. +# endpoint = "http://127.0.0.1:9000" + +# Accept an `http://` endpoint whose host is not a loopback address, or an +# S3 endpoint without `force_path_style`, for the S3 client, the credential +# providers' clients and the instance metadata client alike. Off by default: +# such an endpoint can carry requests, credentials and objects in clear text +# across the network. +# allow_insecure_endpoint = false + +# Use path-style addressing; required by most S3-compatible stores, and by an +# `http://` endpoint unless `allow_insecure_endpoint` is set. +# force_path_style = false + +# Multipart part size in bytes (8 MiB). The enforced range is 5 MiB to 5 GiB, +# the smallest and largest part S3 accepts. Each part must upload within the +# 60 s attempt timeout, so keep it at most about the link's bytes per second +# times 60. +# upload_part_size_bytes = 8388608 + +# Maximum concurrently in-flight part uploads per put. # max_concurrent_uploads = 4 -# Import/Export file operations are disabled by default (secure default). -# Configure allowed directories separately for imports and exports. -# All file paths are canonicalized and must resolve under one of the -# configured roots. Symlinks escaping a root are rejected. -# -# Files are namespaced per account beneath each root: a caller in account -# 111122223333 may only read and write under /111122223333. A path that -# resolves elsewhere is rejected, so tenants sharing an instance cannot read or -# overwrite each other's files. Export refuses to overwrite an existing file. +[import] +# Import and export file operations are disabled until a directory is listed +# here. Every file path is canonicalized and must resolve under one of the +# configured roots; a symlink that escapes a root is rejected. Files are +# namespaced per account beneath each root: a caller in account 111122223333 +# may only read under /111122223333, and a path that resolves elsewhere +# is rejected, so tenants sharing an instance cannot read each other's files. # # On Unix, export files are created with mode 0600, and the directories the # server creates to hold import and export files are created with mode 0700: a @@ -240,48 +754,14 @@ # umask can only narrow these modes. At startup the server warns about a root # with a parent directory that group or others can write to without the # sticky bit, since another user could replace the root through it. -# -# [import] -# paths = ["/var/lib/extenddb/imports"] -# -# [export] -# paths = ["/var/lib/extenddb/exports"] -# -# max_import_bytes = 10737418240 # 10 GB default -# -# Deprecated: import_export_root sets a single root for both import and export. -# It fills only a list that the sections leave empty, so with both [import] and -# [export] present it does nothing, and with neither present it makes the import -# and export roots the same directory. The server logs which of those happened at -# startup. Prefer the sections above; this key will be removed. -# -# It is a top-level key, so it has to appear before the first [section] header of -# this file. Uncommenting it here would place it inside the preceding table and -# the server would refuse to start with "unknown field import_export_root". -# import_export_root = "/var/lib/extenddb/data" -# Runtime settings are managed via `extenddb settings set `, not this file. -# See docs/manuals/05-admin-guide.md (Runtime Settings) for the keys and their defaults. +# Directories imports may read from, for example /var/lib/extenddb/imports. +# Empty means imports are denied. +# paths = [] -# --- Production Configuration Example --- -# Uncomment and adapt the following for production deployments: -# -# [server] -# bind_addr = "0.0.0.0" -# port = 18443 -# -# [server.tls] -# cert_path = "/etc/extenddb/tls/cert.pem" -# key_path = "/etc/extenddb/tls/key.pem" -# -# [storage.postgres] -# connection_string = "postgresql://extenddb:@db.example.com:5432/extenddb_catalog?sslmode=require" -# pool_size = 50 -# catalog_pool_size = 50 -# -# [auth] -# provider = "builtin" -# -# [logging] -# level = "info" -# format = "json" +[export] +# Same rules as [import]. Export refuses to overwrite an existing file. + +# Directories exports may write to, for example /var/lib/extenddb/exports. +# Empty means exports are denied. +# paths = [] diff --git a/tests/cli/test-doc-consistency.sh b/tests/cli/test-doc-consistency.sh index 0b988813b..14be9b442 100755 --- a/tests/cli/test-doc-consistency.sh +++ b/tests/cli/test-doc-consistency.sh @@ -91,22 +91,6 @@ for subcmd in $MANAGE_CMDS; do assert_ok $RC "manage subcommand '$subcmd' documented" done -echo "" -echo "--- Check 2: Sample Config vs. Documentation ---" -echo "" - -if [ -f extenddb.sample.toml ]; then - SAMPLE_KEYS=$(grep -oP '^#?\s*([a-z_]+)\s*=' extenddb.sample.toml | sed 's/^#\s*//' | sed 's/\s*=.*//' | sort -u) - for key in $SAMPLE_KEYS; do - # Skip very generic keys - if [ ${#key} -lt 3 ]; then continue; fi - grep -rq "$key" docs/manuals/ docs/install-from-source.md 2>/dev/null; RC=$? - assert_ok $RC "config key '$key' documented" - done -else - info "extenddb.sample.toml not found — skipping Check 2" -fi - echo "" echo "--- Check 3: Runtime Settings vs. Documentation ---" echo "" diff --git a/website/package.json b/website/package.json index 4ab1c5ffe..de80354c7 100644 --- a/website/package.json +++ b/website/package.json @@ -7,6 +7,8 @@ "build": "docusaurus build", "serve": "docusaurus serve", "clear": "docusaurus clear", + "gen:config": "node scripts/gen-config-reference.mjs", + "check:config": "node scripts/gen-config-reference.mjs --check", "typecheck": "tsc" }, "dependencies": { diff --git a/website/scripts/gen-config-reference.mjs b/website/scripts/gen-config-reference.mjs new file mode 100644 index 000000000..7ba44c249 --- /dev/null +++ b/website/scripts/gen-config-reference.mjs @@ -0,0 +1,213 @@ +#!/usr/bin/env node +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +// Generates docs/configuration.md from extenddb.sample.toml. +// +// The sample is the one hand-written description of every configuration key. +// Its convention, which the Rust tests in crates/config pin to the structs: +// +// - The first comment block of the file is the file header; it is not part +// of the page. +// - `[section]` (or `# [section]`) starts a section. Keys before the first +// header are the top-level keys. +// - A comment block directly under a header, ended by a blank line, is the +// section's introduction and becomes prose. +// - `# key = value` is a key line. The comment lines directly above it are +// its description. A description whose last sentence is "No default." or +// "No default of its own." marks a key whose value is an example: the +// Default column shows "none", that sentence is dropped and the value is +// appended to the description as an example. The Rust tests read the +// same two sentences (`no_default_keys`). A value may not carry a trailing ` #` +// comment outside a string literal; the value is the whole rest of the +// line. +// - Markdown links and code spans in comments pass through to the page. +// +// Usage: node scripts/gen-config-reference.mjs [--check] +// --check regenerate to a string and exit 1 when it differs from the +// committed docs/configuration.md; `npm run gen:config` followed +// by `git diff docs/configuration.md` shows the change. + +import {readFileSync, writeFileSync} from 'node:fs'; +import {dirname, resolve} from 'node:path'; +import {fileURLToPath} from 'node:url'; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..'); +const samplePath = resolve(root, 'extenddb.sample.toml'); +const outputPath = resolve(root, 'docs', 'configuration.md'); + +const KEY_LINE = /^# ([A-Za-z_][A-Za-z0-9_]*) = (.+)$/; +const HEADER_LINE = /^(?:# )?\[([A-Za-z0-9_.]+)\]$/; +const COMMENT_LINE = /^#(?: (.*))?$/; +// The marker sentence that ends the description of a key without a default, +// with the separator before it; `no_default_keys` in +// crates/config/src/sample_toml_support.rs tests the same two sentences. +const NO_DEFAULT = /[;,]?\s*\bno default( of its own)?\.$/i; + +/** Parse the sample into [{name, intro: string[], keys: [{name, value, description, hasDefault}]}]. */ +function parseSample(text) { + const lines = text.split('\n'); + let i = 0; + // Skip the file header: the first comment block and the blank line after it. + while (i < lines.length && lines[i].startsWith('#')) i++; + while (i < lines.length && lines[i].trim() === '') i++; + + const sections = []; + let section = {name: null, intro: [], keys: []}; + sections.push(section); + let pending = []; + let expectIntro = true; + + for (; i < lines.length; i++) { + const line = lines[i]; + const lineNo = i + 1; + const header = line.match(HEADER_LINE); + if (header) { + if (pending.length) throw new Error(`${samplePath}:${lineNo}: comment block before [${header[1]}] is attached to nothing`); + section = {name: header[1], intro: [], keys: []}; + sections.push(section); + expectIntro = true; + continue; + } + const key = line.match(KEY_LINE); + if (key) { + const value = key[2].trim(); + if (hasInlineComment(value)) throw new Error(`${samplePath}:${lineNo}: key ${key[1]} has a trailing comment on its value line; put it in the description above`); + let description = joinComment(pending); + if (!description) throw new Error(`${samplePath}:${lineNo}: key ${key[1]} has no description`); + const hasDefault = !NO_DEFAULT.test(description); + if (!hasDefault) { + description = description.replace(NO_DEFAULT, ''); + if (!/[.!?]$/.test(description)) description += '.'; + description += ` Example: \`${key[1]} = ${value}\``; + } + section.keys.push({name: key[1], value, description, hasDefault}); + pending = []; + expectIntro = false; + continue; + } + if (line.trim() === '') { + if (pending.length) { + if (!expectIntro) throw new Error(`${samplePath}:${lineNo}: comment block is attached to nothing (not a section intro, not above a key)`); + section.intro = pending; + expectIntro = false; + pending = []; + } + continue; + } + const comment = line.match(COMMENT_LINE); + if (!comment) throw new Error(`${samplePath}:${lineNo}: unexpected line: ${line}`); + pending.push(comment[1] ?? ''); + } + if (pending.length) throw new Error(`${samplePath}: trailing comment block is attached to nothing`); + return sections; +} + +/** True when `value` has a ` #` outside a double-quoted string (a TOML inline comment). */ +function hasInlineComment(value) { + let inString = false; + for (let i = 0; i < value.length; i++) { + const c = value[i]; + if (inString) { + if (c === '\\') i++; + else if (c === '"') inString = false; + } else if (c === '"') inString = true; + else if (c === '#' && (i === 0 || value[i - 1] === ' ')) return true; + } + return false; +} + +/** Join comment lines into one string; an empty comment line separates paragraphs. */ +function joinComment(commentLines) { + return commentLines + .join('\n') + .split(/\n\s*\n/) + .map((p) => p.replace(/\s+/g, ' ').trim()) + .filter(Boolean) + .join('\n\n'); +} + +/** Escape MDX-significant characters outside code spans: angle brackets (JSX), braces (expressions), asterisks (emphasis). */ +function escapeMdx(text) { + return text + .split('`') + .map((part, i) => (i % 2 ? part : part.replace(//g, '>').replace(/[{}*]/g, (c) => `\\${c}`))) + .join('`'); +} + +/** A table cell: one line, pipes escaped. */ +function cell(text) { + return escapeMdx(text.replace(/\n\n/g, ' ')).replace(/\|/g, '\\|'); +} + +/** Section introduction prose. */ +function prose(text) { + return escapeMdx(text); +} + +function render(sections) { + const out = []; + out.push('---'); + out.push('description: "Every key of extenddb.toml, its default and what it controls, generated from extenddb.sample.toml."'); + out.push('custom_edit_url: https://github.com/ExtendDB/extenddb/edit/main/extenddb.sample.toml'); + out.push('---'); + out.push(''); + out.push('# Configuration'); + out.push(''); + out.push('This page is generated from [`extenddb.sample.toml`](https://github.com/ExtendDB/extenddb/blob/main/extenddb.sample.toml) by `npm run gen:config` in `website/`; edit the sample, not this file. Tests in the `extenddb-config` crate and in each storage backend crate compare the sample with the configuration structs, so a key listed here exists in the code with the default shown.'); + out.push(''); + out.push('The server reads `extenddb.toml` (or the file named by `--config`) at startup. Scalar keys can also be set through an environment variable: the name is `EXTENDDB__` followed by the key path in upper case with `__` between levels, for example `EXTENDDB__SERVER__PORT=9000` or `EXTENDDB__STORAGE__POSTGRES__CONNECTION_STRING="postgresql://..."`. The list keys (`import.paths`, `export.paths`, `storage.cassandra.contact_points`) and the numeric keys of `[storage.sqlite]` and `[storage.cassandra]` are file only. Precedence, highest first: environment variables, the configuration file, built-in defaults; `extenddb serve --port` overrides `server.port` on top of all three.'); + out.push(''); + out.push('The keys below are static: a change takes effect at the next server start. Settings that change on a running server (log level, control plane delay, throttling at runtime) are set with `extenddb settings set` and are listed under [Runtime Settings](./manuals/05-admin-guide.md#runtime-settings) in the administration guide.'); + for (const section of sections) { + out.push(''); + out.push(section.name === null ? '## Top-level keys' : `## \`[${section.name}]\``); + if (section.intro.length) { + out.push(''); + out.push(prose(joinComment(section.intro))); + } + if (!section.keys.length) continue; + out.push(''); + out.push('| Key | Default | Description |'); + out.push('|-----|---------|-------------|'); + for (const key of section.keys) { + // A long default (the PostgreSQL connection string) would set the column + // width for the whole table; it moves into the description instead. + let def = 'none'; + let desc = key.description; + if (key.hasDefault && key.value.length > 40) { + def = 'see description'; + desc += ` Default: \`${key.name} = ${key.value}\``; + } else if (key.hasDefault) { + def = `\`${key.value}\``; + } + out.push(`| \`${key.name}\` | ${def} | ${cell(desc)} |`); + } + } + out.push(''); + return out.join('\n'); +} + +function main() { + const check = process.argv.includes('--check'); + const generated = render(parseSample(readFileSync(samplePath, 'utf8'))); + if (!check) { + writeFileSync(outputPath, generated); + console.log(`wrote ${outputPath}`); + return; + } + let current = ''; + try { + current = readFileSync(outputPath, 'utf8'); + } catch { + // Missing file: reported as out of date below. + } + if (current === generated) { + console.log('docs/configuration.md matches extenddb.sample.toml'); + return; + } + console.error('docs/configuration.md is out of date; run `npm run gen:config` in website/ and commit the result.'); + process.exitCode = 1; +} + +main(); diff --git a/website/sidebars.ts b/website/sidebars.ts index 7ad776e3e..b0259ebd1 100644 --- a/website/sidebars.ts +++ b/website/sidebars.ts @@ -91,12 +91,7 @@ const sidebars: SidebarsConfig = { {type: 'doc', id: 'differences-from-dynamodb', label: 'Differences from DynamoDB'}, {type: 'doc', id: 'dynamodb-limits', label: 'Limits'}, {type: 'doc', id: 'versioning', label: 'Versioning and support'}, - { - type: 'link', - label: 'Configuration', - href: '/manuals/admin-guide/#configuration-reference', - description: 'Every key in extenddb.toml, its default and what it controls (in the administration guide).', - }, + {type: 'doc', id: 'configuration', label: 'Configuration'}, {type: 'doc', id: 'troubleshooting', label: 'Troubleshooting'}, ], }, diff --git a/website/src/css/custom.css b/website/src/css/custom.css index 182fa769c..516e2f4e1 100644 --- a/website/src/css/custom.css +++ b/website/src/css/custom.css @@ -289,4 +289,20 @@ html { min-width: 0; overflow-wrap: break-word; } + /* On the configuration page, key names and defaults stay whole: a key + split into syllables or a number split across lines is harder to read + than a sideways scroll. The description column keeps a floor so it stays + readable while the table scrolls inside its own box. Scoped to that page + by the class Docusaurus puts on , so other pages' tables keep their + widths. */ + html.docs-doc-id-configuration article table td:nth-child(1) code, + html.docs-doc-id-configuration article table td:nth-child(2) code { + white-space: nowrap; + } + html.docs-doc-id-configuration article table td:nth-child(3) { + min-width: 14rem; + } + html.docs-doc-id-configuration article table td:nth-child(3) code { + overflow-wrap: anywhere; + } }