Files
varde/varde-daemon/src/config.rs
T
Bendik LynghaugandClaude Fable 5 ad69f7d884 Migrate to iroh 1.0 and iroh-blobs 0.103
The 0.35 pin's rationale ("the post-0.35 rewrite is not yet production
quality") expired when iroh hit 1.0 in June 2026: the rewrite line
(0.103) is now the production line and the only one receiving fixes.

The rewrite replaced wrappable store traits with an irpc-based API, so
the seams moved:

- shaped.rs: the 440-line ShapedStore trait wrapper becomes a provider
  event handler. Trust gating (untrusted peers see only openly-served
  hashes) now intercepts requests before any bytes move; upload rate
  limiting rides the provider's Throttle hook; upload progress events
  come from per-request update streams. The TokenBucket is unchanged.
- store.rs: FsStore's API handle replaces the store traits, and the
  LocalPool machinery for non-Send futures is gone. GC is now the
  store's built-in periodic mark-and-sweep, fed by a pin-roots snapshot
  via the protect callback (new config knob gc_interval_secs, default
  300); the on-demand Gc request answers Unimplemented, and the gc
  conformance test polls the sweep instead.
- transfer.rs: BlobsProtocol + Router replace handle_connection, the
  new multi-provider Downloader replaces the old queue, and mdns
  discovery moved to the iroh-mdns-address-lookup crate (it left iroh
  core in 1.0). Ticket-embedded provider addresses feed a MemoryLookup
  address book. Endpoint presets: Minimal (LAN-only default) or N0
  (wan_upload), preserving the old relay posture.
- Node* became Endpoint* throughout; announcement signatures use iroh's
  own Signature type (ed25519-dalek dep dropped); iroh-io dropped.

Known regression: max_download_bytes_per_sec is currently not enforced
— download shaping rode the old store's batch writer and 0.103's
downloader has no equivalent seam yet.

Announcement wire format note: EndpointAddr serializes differently than
NodeAddr, so pre- and post-migration daemons won't parse each other's
LAN announcements. Announcements are live-only, nothing stored breaks.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-16 14:03:15 +02:00

260 lines
8.9 KiB
Rust

//! Daemon configuration.
//!
//! Precedence: CLI flags > environment > config file > defaults.
//! The daemon must run with an empty (or absent) config file.
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use serde::Deserialize;
/// Fully resolved runtime configuration.
#[derive(Debug, Clone)]
pub struct Config {
/// Directory holding the blob store, metadata and secret key.
pub store_dir: PathBuf,
/// Path of the unix socket to serve the API on.
pub socket_path: PathBuf,
/// Upload rate cap in bytes/sec. 0 disables serving entirely.
pub max_upload_bytes_per_sec: u64,
/// Download rate cap in bytes/sec. 0 means unlimited.
pub max_download_bytes_per_sec: u64,
/// Whether LAN discovery (mDNS-style) is enabled.
pub discovery: bool,
/// Whether any WAN (non-link-local) upload is permitted. Default off:
/// LAN-only posture with zero WAN upload.
pub wan_upload: bool,
/// Interval of the store's built-in garbage collector in seconds.
/// Since iroh-blobs 0.103 there is no on-demand gc; unpinned blobs
/// are swept by this loop.
pub gc_interval_secs: u64,
}
/// Serde image of the TOML config file. Everything optional so an empty
/// file (or none at all) is valid.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct FileConfig {
store_dir: Option<PathBuf>,
socket_path: Option<PathBuf>,
max_upload_bytes_per_sec: Option<u64>,
max_download_bytes_per_sec: Option<u64>,
discovery: Option<bool>,
wan_upload: Option<bool>,
gc_interval_secs: Option<u64>,
}
/// Values collected from CLI flags; `None` means "not given".
#[derive(Debug, Default)]
pub struct Overrides {
pub config_path: Option<PathBuf>,
pub store_dir: Option<PathBuf>,
pub socket_path: Option<PathBuf>,
}
/// Whether the daemon runs as a system service or a per-user service.
/// Decides default paths only; everything can be overridden.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
System,
User,
}
impl Mode {
/// System mode when running as root, user mode otherwise.
pub fn detect() -> Mode {
// SAFETY: geteuid has no preconditions and cannot fail.
if unsafe { libc_geteuid() } == 0 {
Mode::System
} else {
Mode::User
}
}
fn default_store_dir(self) -> PathBuf {
match self {
Mode::System => PathBuf::from("/var/lib/varde"),
Mode::User => xdg_dir("XDG_DATA_HOME", ".local/share").join("varde"),
}
}
fn default_socket_path(self) -> PathBuf {
match self {
Mode::System => PathBuf::from("/run/varde/varde.sock"),
Mode::User => match std::env::var_os("XDG_RUNTIME_DIR") {
Some(dir) => PathBuf::from(dir).join("varde.sock"),
// No XDG_RUNTIME_DIR (rare outside a session): fall back
// next to the store so the daemon still starts.
None => Mode::User.default_store_dir().join("varde.sock"),
},
}
}
fn default_config_path(self) -> PathBuf {
match self {
Mode::System => PathBuf::from("/etc/varde/config.toml"),
Mode::User => xdg_dir("XDG_CONFIG_HOME", ".config").join("varde/config.toml"),
}
}
}
fn xdg_dir(var: &str, home_rel: &str) -> PathBuf {
if let Some(dir) = std::env::var_os(var) {
return PathBuf::from(dir);
}
let home = std::env::var_os("HOME").unwrap_or_else(|| "/".into());
PathBuf::from(home).join(home_rel)
}
// Minimal FFI shim instead of pulling in the libc crate for one call.
extern "C" {
#[link_name = "geteuid"]
fn libc_geteuid() -> u32;
}
impl Config {
/// Resolve configuration with full precedence:
/// `overrides` (flags) > environment > config file > mode defaults.
pub fn load(mode: Mode, overrides: &Overrides) -> Result<Config> {
let config_path = overrides
.config_path
.clone()
.or_else(|| std::env::var_os("VARDE_CONFIG").map(PathBuf::from))
.unwrap_or_else(|| mode.default_config_path());
// An explicitly named config file must exist; the default one is
// allowed to be absent.
let explicit =
overrides.config_path.is_some() || std::env::var_os("VARDE_CONFIG").is_some();
let file = Self::read_file(&config_path, explicit)?;
let env_path = |var: &str| std::env::var_os(var).map(PathBuf::from);
let env_u64 = |var: &str| -> Result<Option<u64>> {
match std::env::var(var) {
Ok(v) => {
Ok(Some(v.parse().with_context(|| {
format!("{var} must be an integer, got {v:?}")
})?))
}
Err(_) => Ok(None),
}
};
let env_bool = |var: &str| -> Result<Option<bool>> {
match std::env::var(var) {
Ok(v) => {
Ok(Some(v.parse().with_context(|| {
format!("{var} must be true/false, got {v:?}")
})?))
}
Err(_) => Ok(None),
}
};
Ok(Config {
store_dir: overrides
.store_dir
.clone()
.or_else(|| env_path("VARDE_STORE"))
.or(file.store_dir)
.unwrap_or_else(|| mode.default_store_dir()),
socket_path: overrides
.socket_path
.clone()
.or_else(|| env_path("VARDE_SOCKET"))
.or(file.socket_path)
.unwrap_or_else(|| mode.default_socket_path()),
max_upload_bytes_per_sec: env_u64("VARDE_MAX_UPLOAD")?
.or(file.max_upload_bytes_per_sec)
// Conservative default: 10 MB/s on LAN.
.unwrap_or(10 * 1024 * 1024),
max_download_bytes_per_sec: env_u64("VARDE_MAX_DOWNLOAD")?
.or(file.max_download_bytes_per_sec)
.unwrap_or(0),
discovery: env_bool("VARDE_DISCOVERY")?
.or(file.discovery)
.unwrap_or(true),
wan_upload: env_bool("VARDE_WAN_UPLOAD")?
.or(file.wan_upload)
.unwrap_or(false),
gc_interval_secs: env_u64("VARDE_GC_INTERVAL")?
.or(file.gc_interval_secs)
.unwrap_or(300),
})
}
fn read_file(path: &Path, must_exist: bool) -> Result<FileConfig> {
match std::fs::read_to_string(path) {
Ok(text) => toml::from_str(&text)
.with_context(|| format!("parsing config file {}", path.display())),
Err(e) if e.kind() == std::io::ErrorKind::NotFound && !must_exist => {
Ok(FileConfig::default())
}
Err(e) => Err(e).with_context(|| format!("reading config file {}", path.display())),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
// Env-var manipulation is process-global, so these tests only use
// overrides and files, never set_var.
#[test]
fn empty_config_file_is_valid() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(&path, "").unwrap();
let overrides = Overrides {
config_path: Some(path),
..Default::default()
};
let cfg = Config::load(Mode::User, &overrides).unwrap();
assert!(!cfg.wan_upload, "WAN upload must default off");
assert!(cfg.discovery, "discovery defaults on");
assert_eq!(cfg.max_upload_bytes_per_sec, 10 * 1024 * 1024);
}
#[test]
fn missing_default_config_is_fine() {
let cfg = Config::load(Mode::User, &Overrides::default()).unwrap();
assert!(cfg.socket_path.to_string_lossy().ends_with("varde.sock"));
}
#[test]
fn missing_explicit_config_errors() {
let overrides = Overrides {
config_path: Some(PathBuf::from("/nonexistent/varde.toml")),
..Default::default()
};
assert!(Config::load(Mode::User, &overrides).is_err());
}
#[test]
fn flags_beat_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(&path, "store_dir = \"/from/file\"\n").unwrap();
let overrides = Overrides {
config_path: Some(path),
store_dir: Some(PathBuf::from("/from/flag")),
..Default::default()
};
let cfg = Config::load(Mode::User, &overrides).unwrap();
assert_eq!(cfg.store_dir, PathBuf::from("/from/flag"));
}
#[test]
fn unknown_keys_rejected() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(&path, "no_such_key = 1\n").unwrap();
let overrides = Overrides {
config_path: Some(path),
..Default::default()
};
assert!(Config::load(Mode::User, &overrides).is_err());
}
}