mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Moved the workspace to the root, Added the build scripts, ARM64 releases and the Docker image
Source/'s content is at the root now, Source/README.md merged into readme.md. Scripts at the root: build.ps1, test.ps1 (was check.ps1), release.ps1 (over release.py) and clean.ps1. Everything is LF except the .ps1 files. CI (.github/workflows/ci.yml) runs on a v* tag or by hand: the checks, then a release for Windows x64 and ARM64 and Linux x64 and ARM64, each on its own kind of runner, the archives kept as artifacts. release.py names the platform from the Rust host, make_wheel.py tags the wheel from the library's header. docker/: the server's image (built from source, the tools beside it, uid 10001), compose.yml and test.sh. CI builds amd64 and arm64 natively, checks them, and on a tag pushes them to ghcr.io with an index for <version> and latest. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,325 @@
|
||||
//! The server's config: a TOML file, read and checked in one go.
|
||||
//!
|
||||
//! - [`Server`]: where it listens, its files, its topics, its database.
|
||||
//! - [`Retention`]: how long each topic's messages are kept.
|
||||
//! - [`Replication`]: the servers it sends to and takes from, what it
|
||||
//! replicates, how often.
|
||||
//! - [`Role`]: what certificates with a role may do; [`Permissions`]: what
|
||||
//! a certificate's roles allow together.
|
||||
//!
|
||||
//! Who connects is the certificate's (`bakashrot-pki`): its name is its
|
||||
//! node, its roles are looked up here. Peers too: what's replicated with a
|
||||
//! peer is its roles'. The file, every key and its default:
|
||||
//! `docs/config.md`.
|
||||
//!
|
||||
//! Every value is checked as serde reads it, so a wrong one is refused with
|
||||
//! its line.
|
||||
|
||||
mod roles;
|
||||
mod values;
|
||||
|
||||
pub use roles::{NameList, Permissions, Role};
|
||||
|
||||
use bakashrot_proto::names::{is_valid_name, is_valid_pattern, names_equal, pattern_matches};
|
||||
use indexmap::IndexMap;
|
||||
use serde::{Deserialize, Deserializer, de::Error as _};
|
||||
use std::fmt;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
use values::{DURATION_HELP, NAME_HELP, parse_age};
|
||||
|
||||
/// What's wrong with a config, in words: where (the file, the line) and why.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Error(String);
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {}
|
||||
|
||||
/// A result of this crate.
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// A server's config.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Config {
|
||||
/// `[server]`.
|
||||
pub server: Server,
|
||||
/// `[retention]`.
|
||||
#[serde(default)]
|
||||
pub retention: Retention,
|
||||
/// `[replication]`.
|
||||
#[serde(default)]
|
||||
pub replication: Replication,
|
||||
/// `[roles.<name>]`, in the file's order.
|
||||
#[serde(default, deserialize_with = "roles")]
|
||||
pub roles: Vec<Role>,
|
||||
}
|
||||
|
||||
/// `[server]`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Server {
|
||||
/// The address and port it listens on.
|
||||
#[serde(deserialize_with = "values::listen")]
|
||||
pub listen: SocketAddr,
|
||||
/// The CA's certificate.
|
||||
pub ca: PathBuf,
|
||||
/// The server's certificate.
|
||||
pub certificate: PathBuf,
|
||||
/// The server's key.
|
||||
pub key: PathBuf,
|
||||
/// The CA's CRL, watched; none: nothing revoked.
|
||||
#[serde(default)]
|
||||
pub crl: Option<PathBuf>,
|
||||
/// The SQLite database; `bakashrot.sqlite` by default.
|
||||
#[serde(default = "defaults::database")]
|
||||
pub database: PathBuf,
|
||||
/// The topics clients push to, by name.
|
||||
#[serde(default, deserialize_with = "values::topic_names")]
|
||||
pub topics: Vec<String>,
|
||||
/// How hard a push is made sure to be on disk.
|
||||
#[serde(default)]
|
||||
pub synchronous: Synchronous,
|
||||
/// The biggest attachment taken, in bytes; 0: none. 1G by default.
|
||||
#[serde(
|
||||
default = "defaults::max_attachment_size",
|
||||
deserialize_with = "values::size"
|
||||
)]
|
||||
pub max_attachment_size: u64,
|
||||
/// How often messages past their age are deleted; 1m by default.
|
||||
#[serde(
|
||||
default = "defaults::retention_interval",
|
||||
deserialize_with = "values::duration"
|
||||
)]
|
||||
pub retention_interval: Duration,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// Whether `topic` is one of its topics.
|
||||
pub fn has_topic(&self, topic: &str) -> bool {
|
||||
self.topics.iter().any(|own| names_equal(own, topic))
|
||||
}
|
||||
}
|
||||
|
||||
/// How hard the database makes sure a push is on disk before answering it
|
||||
/// (SQLite's `synchronous`).
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
|
||||
#[serde(try_from = "String")]
|
||||
pub enum Synchronous {
|
||||
/// Every commit flushed: an answered push survives a power loss. The
|
||||
/// default.
|
||||
#[default]
|
||||
Full,
|
||||
/// Flushed about once a second: faster, a power loss loses the last
|
||||
/// second or so of answered pushes.
|
||||
Normal,
|
||||
}
|
||||
|
||||
impl TryFrom<String> for Synchronous {
|
||||
type Error = String;
|
||||
|
||||
fn try_from(text: String) -> std::result::Result<Self, String> {
|
||||
match text.trim().to_ascii_lowercase().as_str() {
|
||||
"full" => Ok(Synchronous::Full),
|
||||
"normal" => Ok(Synchronous::Normal),
|
||||
"off" => Err(
|
||||
"\"off\" isn't allowed: a power loss could corrupt the database. \
|
||||
\"full\", or \"normal\" to only risk the last second of messages"
|
||||
.into(),
|
||||
),
|
||||
"extra" => Err("\"extra\" does nothing more than \"full\" here: write \"full\"".into()),
|
||||
_ => Err(format!("'{text}' isn't \"full\" or \"normal\"")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `[retention]`: how long each topic's messages are kept, from when they
|
||||
/// were first pushed.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
|
||||
#[serde(try_from = "IndexMap<String, toml::Value>")]
|
||||
pub struct Retention {
|
||||
/// Names and patterns with their age (none: forever), in the file's
|
||||
/// order.
|
||||
lines: Vec<(String, Option<Duration>)>,
|
||||
}
|
||||
|
||||
impl TryFrom<IndexMap<String, toml::Value>> for Retention {
|
||||
type Error = String;
|
||||
|
||||
fn try_from(table: IndexMap<String, toml::Value>) -> std::result::Result<Self, String> {
|
||||
let mut lines: Vec<(String, Option<Duration>)> = Vec::with_capacity(table.len());
|
||||
for (key, value) in table {
|
||||
if !is_valid_pattern(&key) && !is_valid_name(&key) {
|
||||
return Err(format!(
|
||||
"'{key}' isn't a topic name or a pattern ({NAME_HELP})"
|
||||
));
|
||||
}
|
||||
if lines.iter().any(|(before, _)| names_equal(before, &key)) {
|
||||
return Err(format!("'{key}' is given twice"));
|
||||
}
|
||||
let age = match &value {
|
||||
toml::Value::String(text) => parse_age(text),
|
||||
toml::Value::Table(_) => {
|
||||
return Err(format!(
|
||||
"'{key}' is a table: quote names with dots, \"{key}.x\" = \"30d\""
|
||||
));
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let age = age.ok_or_else(|| {
|
||||
format!("{key} = {value} isn't an age: {DURATION_HELP}, or \"forever\"")
|
||||
})?;
|
||||
lines.push((key, age));
|
||||
}
|
||||
Ok(Retention { lines })
|
||||
}
|
||||
}
|
||||
|
||||
impl Retention {
|
||||
/// How long `topic`'s messages are kept, `None` for forever: its name's
|
||||
/// line, else the first pattern matching it, else `*`'s, else forever.
|
||||
pub fn age(&self, topic: &str) -> Option<Duration> {
|
||||
let line = |found: fn(&str, &str) -> bool| {
|
||||
self.lines
|
||||
.iter()
|
||||
.find(|(key, _)| key != "*" && found(key, topic))
|
||||
};
|
||||
line(names_equal)
|
||||
.or_else(|| line(|key, topic| is_valid_pattern(key) && pattern_matches(key, topic)))
|
||||
.or_else(|| self.lines.iter().find(|(key, _)| key == "*"))
|
||||
.and_then(|(_, age)| *age)
|
||||
}
|
||||
}
|
||||
|
||||
/// `[replication]`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct Replication {
|
||||
/// The servers it dials and sends to (`host:port`). What's sent to
|
||||
/// each is its roles' `send_*`.
|
||||
#[serde(deserialize_with = "values::peers")]
|
||||
pub push_to: Vec<String>,
|
||||
/// The servers it takes replicated messages from: IP addresses or
|
||||
/// hostnames, `*` for all; none by default. What's taken is their
|
||||
/// roles' `accept_*`.
|
||||
#[serde(deserialize_with = "values::hosts")]
|
||||
pub accept_from: Vec<String>,
|
||||
/// The only topics replicated at all, whatever the roles say (an edge
|
||||
/// node's filter); none: no filter.
|
||||
pub replicated_topics: Option<NameList>,
|
||||
/// How long to wait before dialing a peer again; 10s by default.
|
||||
#[serde(deserialize_with = "values::duration")]
|
||||
pub retry_delay: Duration,
|
||||
/// How long a link waits, once nothing was left to send, before it
|
||||
/// looks again; 5s by default.
|
||||
#[serde(deserialize_with = "values::duration")]
|
||||
pub sync_interval: Duration,
|
||||
/// The most messages sent to a peer per packet; 1000 by default.
|
||||
#[serde(deserialize_with = "values::batch_size")]
|
||||
pub batch_size: u32,
|
||||
}
|
||||
|
||||
impl Default for Replication {
|
||||
fn default() -> Self {
|
||||
Replication {
|
||||
push_to: Vec::new(),
|
||||
accept_from: Vec::new(),
|
||||
replicated_topics: None,
|
||||
retry_delay: Duration::from_secs(10),
|
||||
sync_interval: Duration::from_secs(5),
|
||||
batch_size: 1000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `[server]`'s defaults.
|
||||
mod defaults {
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
pub(crate) fn database() -> PathBuf {
|
||||
"bakashrot.sqlite".into()
|
||||
}
|
||||
pub(crate) fn max_attachment_size() -> u64 {
|
||||
1 << 30
|
||||
}
|
||||
pub(crate) fn retention_interval() -> Duration {
|
||||
Duration::from_secs(60)
|
||||
}
|
||||
}
|
||||
|
||||
/// `[roles.*]`: each section's name is its role's, none twice.
|
||||
fn roles<'de, D: Deserializer<'de>>(reader: D) -> std::result::Result<Vec<Role>, D::Error> {
|
||||
let table = IndexMap::<String, Role>::deserialize(reader)?;
|
||||
let mut roles: Vec<Role> = Vec::with_capacity(table.len());
|
||||
for (name, mut role) in table {
|
||||
if !is_valid_name(&name) {
|
||||
return Err(D::Error::custom(format!(
|
||||
"'{name}' isn't a role name ({NAME_HELP})"
|
||||
)));
|
||||
}
|
||||
if let Some(before) = roles.iter().find(|role| names_equal(&role.name, &name)) {
|
||||
return Err(D::Error::custom(format!(
|
||||
"'{}' and '{name}' are the same role (case doesn't matter)",
|
||||
before.name
|
||||
)));
|
||||
}
|
||||
role.name = name;
|
||||
roles.push(role);
|
||||
}
|
||||
Ok(roles)
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Reads the config file at `path`. Relative paths in it are from its
|
||||
/// folder.
|
||||
pub fn load(path: &Path) -> Result<Config> {
|
||||
let in_file = |error: &dyn fmt::Display| Error(format!("{}: {error}", path.display()));
|
||||
let text = std::fs::read_to_string(path).map_err(|error| in_file(&error))?;
|
||||
let mut config = Config::parse(&text).map_err(|error| in_file(&error))?;
|
||||
let folder = path.parent().unwrap_or(Path::new(""));
|
||||
let server = &mut config.server;
|
||||
for file in [
|
||||
&mut server.ca,
|
||||
&mut server.certificate,
|
||||
&mut server.key,
|
||||
&mut server.database,
|
||||
]
|
||||
.into_iter()
|
||||
.chain(server.crl.as_mut())
|
||||
{
|
||||
*file = folder.join(&*file);
|
||||
}
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// Reads a config, paths as they're written.
|
||||
pub fn parse(text: &str) -> Result<Config> {
|
||||
toml::from_str(text).map_err(|error| Error(error.to_string().trim_end().to_owned()))
|
||||
}
|
||||
|
||||
/// What a certificate with these roles may do: everything its roles
|
||||
/// with a section allow. `None` if none has one: it's refused.
|
||||
pub fn permissions<S: AsRef<str>>(&self, roles: &[S]) -> Option<Permissions> {
|
||||
let roles: Vec<Role> = self
|
||||
.roles
|
||||
.iter()
|
||||
.filter(|role| {
|
||||
roles
|
||||
.iter()
|
||||
.any(|own| names_equal(own.as_ref(), &role.name))
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
(!roles.is_empty()).then(|| Permissions {
|
||||
roles,
|
||||
replicated_topics: self.replication.replicated_topics.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
//! Roles, and what a certificate's roles allow together.
|
||||
|
||||
use crate::values::check_names;
|
||||
use bakashrot_proto::names::{names_equal, pattern_matches};
|
||||
use serde::Deserialize;
|
||||
|
||||
/// Topic or node names and patterns (`sensors.*`, `*` for all), none twice.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
|
||||
#[serde(try_from = "Vec<String>")]
|
||||
pub struct NameList(Vec<String>);
|
||||
|
||||
impl TryFrom<Vec<String>> for NameList {
|
||||
type Error = String;
|
||||
|
||||
fn try_from(list: Vec<String>) -> Result<Self, String> {
|
||||
check_names(&list, true)?;
|
||||
Ok(NameList(list))
|
||||
}
|
||||
}
|
||||
|
||||
impl NameList {
|
||||
/// `*`: every name.
|
||||
pub fn every() -> NameList {
|
||||
NameList(vec!["*".to_owned()])
|
||||
}
|
||||
|
||||
/// Whether `name` is in it: one of its names, or matched by one of its
|
||||
/// patterns (without case).
|
||||
pub fn matches(&self, name: &str) -> bool {
|
||||
self.0
|
||||
.iter()
|
||||
.any(|entry| names_equal(entry, name) || pattern_matches(entry, name))
|
||||
}
|
||||
|
||||
/// Whether it has nothing: matches nothing.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
|
||||
/// Its names and patterns, as written.
|
||||
pub fn entries(&self) -> &[String] {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// A `[roles.<name>]` section: what certificates with this role may do.
|
||||
/// Every key is optional.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Role {
|
||||
/// The role, as certificates say it (compared without case): the
|
||||
/// section's name.
|
||||
#[serde(skip)]
|
||||
pub name: String,
|
||||
/// The topics it may push to, always as its own node.
|
||||
#[serde(default)]
|
||||
pub push_topics: NameList,
|
||||
/// The topics it may read the messages of.
|
||||
#[serde(default)]
|
||||
pub read_topics: NameList,
|
||||
/// Whether it may run read-only SQL, which reads every topic.
|
||||
#[serde(default)]
|
||||
pub query: bool,
|
||||
/// Replication: the topics sent to it.
|
||||
#[serde(default)]
|
||||
pub send_topics: NameList,
|
||||
/// Replication: the topics taken from it.
|
||||
#[serde(default)]
|
||||
pub accept_topics: NameList,
|
||||
/// Replication: the nodes whose messages are sent to it (all by default).
|
||||
#[serde(default = "NameList::every")]
|
||||
pub send_nodes: NameList,
|
||||
/// Replication: the nodes whose messages are taken from it (all by
|
||||
/// default).
|
||||
#[serde(default = "NameList::every")]
|
||||
pub accept_nodes: NameList,
|
||||
}
|
||||
|
||||
/// What a certificate may do: everything one of its roles allows, each role
|
||||
/// on its own (a role's topics go with that role's nodes), replication
|
||||
/// within the server's `replicated_topics`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Permissions {
|
||||
pub(crate) roles: Vec<Role>,
|
||||
pub(crate) replicated_topics: Option<NameList>,
|
||||
}
|
||||
|
||||
impl Permissions {
|
||||
/// Its roles that this server has a section for.
|
||||
pub fn roles(&self) -> impl Iterator<Item = &str> {
|
||||
self.roles.iter().map(|role| role.name.as_str())
|
||||
}
|
||||
|
||||
/// Whether it may push to `topic`.
|
||||
pub fn can_push(&self, topic: &str) -> bool {
|
||||
self.roles
|
||||
.iter()
|
||||
.any(|role| role.push_topics.matches(topic))
|
||||
}
|
||||
|
||||
/// Whether it may read `topic`'s messages.
|
||||
pub fn can_read(&self, topic: &str) -> bool {
|
||||
self.roles
|
||||
.iter()
|
||||
.any(|role| role.read_topics.matches(topic))
|
||||
}
|
||||
|
||||
/// Whether it may run read-only SQL.
|
||||
pub fn can_query(&self) -> bool {
|
||||
self.roles.iter().any(|role| role.query)
|
||||
}
|
||||
|
||||
/// Whether `node`'s messages in `topic` are sent to it.
|
||||
pub fn sends(&self, topic: &str, node: &str) -> bool {
|
||||
self.replicated(topic)
|
||||
&& self
|
||||
.roles
|
||||
.iter()
|
||||
.any(|role| role.send_topics.matches(topic) && role.send_nodes.matches(node))
|
||||
}
|
||||
|
||||
/// Whether `node`'s messages in `topic` are taken from it.
|
||||
pub fn accepts(&self, topic: &str, node: &str) -> bool {
|
||||
self.replicated(topic)
|
||||
&& self
|
||||
.roles
|
||||
.iter()
|
||||
.any(|role| role.accept_topics.matches(topic) && role.accept_nodes.matches(node))
|
||||
}
|
||||
|
||||
/// The topics and the nodes taken from it, as `SyncState` lists them:
|
||||
/// its roles' `accept_*` (of those that accept topics), none twice.
|
||||
/// What's taken is still [`Permissions::accepts`]'.
|
||||
pub fn accepted(&self) -> (Vec<String>, Vec<String>) {
|
||||
let (mut topics, mut nodes) = (Vec::<String>::new(), Vec::<String>::new());
|
||||
for role in self
|
||||
.roles
|
||||
.iter()
|
||||
.filter(|role| !role.accept_topics.is_empty())
|
||||
{
|
||||
for (list, entries) in [
|
||||
(&mut topics, role.accept_topics.entries()),
|
||||
(&mut nodes, role.accept_nodes.entries()),
|
||||
] {
|
||||
for entry in entries {
|
||||
if !list.iter().any(|known| names_equal(known, entry)) {
|
||||
list.push(entry.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(topics, nodes)
|
||||
}
|
||||
|
||||
/// Whether it replicates at all: a peer.
|
||||
pub fn replicates(&self) -> bool {
|
||||
self.roles
|
||||
.iter()
|
||||
.any(|role| !role.send_topics.is_empty() || !role.accept_topics.is_empty())
|
||||
}
|
||||
|
||||
fn replicated(&self, topic: &str) -> bool {
|
||||
self.replicated_topics
|
||||
.as_ref()
|
||||
.is_none_or(|topics| topics.matches(topic))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
//! The values that need more than a type: durations, ages, sizes,
|
||||
//! addresses, names.
|
||||
|
||||
use bakashrot_proto::limits::{MAX_ATTACHMENT_SIZE, MAX_MESSAGES_PER_PACKET};
|
||||
use bakashrot_proto::names::{is_valid_name, is_valid_name_or_pattern, names_equal};
|
||||
use serde::de::Error as _;
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use std::net::{Ipv6Addr, SocketAddr};
|
||||
use std::time::Duration;
|
||||
|
||||
/// What a duration looks like, for errors.
|
||||
pub(crate) const DURATION_HELP: &str = "numbers with a unit (s m h d w), like 30s or 1d12h";
|
||||
|
||||
/// What a name looks like, for errors.
|
||||
pub(crate) const NAME_HELP: &str = "1-64 of A-Z a-z 0-9 _ . -, not only digits; patterns: * and ?";
|
||||
|
||||
/// A duration: numbers with a unit, added up (`1d12h`). Units `s m h d w`,
|
||||
/// without case. More than 0.
|
||||
pub(crate) fn parse_duration(text: &str) -> Option<Duration> {
|
||||
let mut seconds: u64 = 0;
|
||||
let mut number: Option<u64> = None;
|
||||
for c in text.trim().chars() {
|
||||
if let Some(digit) = c.to_digit(10) {
|
||||
number = Some(
|
||||
number
|
||||
.unwrap_or(0)
|
||||
.checked_mul(10)?
|
||||
.checked_add(digit.into())?,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
let unit: u64 = match c.to_ascii_lowercase() {
|
||||
's' => 1,
|
||||
'm' => 60,
|
||||
'h' => 3600,
|
||||
'd' => 86_400,
|
||||
'w' => 604_800,
|
||||
_ => return None,
|
||||
};
|
||||
seconds = seconds.checked_add(number.take()?.checked_mul(unit)?)?;
|
||||
}
|
||||
if number.is_some() || seconds == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(Duration::from_secs(seconds))
|
||||
}
|
||||
|
||||
/// A retention age: a duration, or `forever` (`Some(None)`).
|
||||
pub(crate) fn parse_age(text: &str) -> Option<Option<Duration>> {
|
||||
if text.trim().eq_ignore_ascii_case("forever") {
|
||||
return Some(None);
|
||||
}
|
||||
parse_duration(text).map(Some)
|
||||
}
|
||||
|
||||
/// A size: bytes (a number), or text with K, M, G or T (1024-based, without
|
||||
/// case), up to `MAX_ATTACHMENT_SIZE`. 0 is a size.
|
||||
pub(crate) fn parse_size(value: &toml::Value) -> Option<u64> {
|
||||
let size = match value {
|
||||
toml::Value::Integer(bytes) => u64::try_from(*bytes).ok()?,
|
||||
toml::Value::String(text) => {
|
||||
let text = text.trim();
|
||||
let (digits, unit) = match text.char_indices().last()? {
|
||||
(at, c) if c.is_ascii_alphabetic() => (&text[..at], c.to_ascii_uppercase()),
|
||||
_ => (text, 'B'),
|
||||
};
|
||||
let shift = match unit {
|
||||
'B' => 0,
|
||||
'K' => 10,
|
||||
'M' => 20,
|
||||
'G' => 30,
|
||||
'T' => 40,
|
||||
_ => return None,
|
||||
};
|
||||
if digits.is_empty() || !digits.bytes().all(|c| c.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
digits.parse::<u64>().ok()?.checked_mul(1 << shift)?
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
(size <= MAX_ATTACHMENT_SIZE).then_some(size)
|
||||
}
|
||||
|
||||
/// Whether `text` is a host and a port: `10.0.0.2:7000`,
|
||||
/// `server-2.lan:7000`, `[fd00::2]:7000`. The port isn't 0.
|
||||
pub(crate) fn is_peer_address(text: &str) -> bool {
|
||||
let Some((host, port)) = text.rsplit_once(':') else {
|
||||
return false;
|
||||
};
|
||||
let port = port.parse::<u16>().is_ok_and(|port| port != 0);
|
||||
let host = match host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) {
|
||||
Some(v6) => v6.parse::<Ipv6Addr>().is_ok(),
|
||||
None => is_hostname(host),
|
||||
};
|
||||
port && host
|
||||
}
|
||||
|
||||
/// A hostname or an IPv4 address: letters, digits, dots and dashes.
|
||||
fn is_hostname(host: &str) -> bool {
|
||||
!host.is_empty()
|
||||
&& host
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == b'.' || c == b'-')
|
||||
}
|
||||
|
||||
// As serde reads them (`deserialize_with`): a value that's wrong fails
|
||||
// there, and toml says on which line.
|
||||
|
||||
/// A duration, more than 0.
|
||||
pub(crate) fn duration<'de, D: Deserializer<'de>>(reader: D) -> Result<Duration, D::Error> {
|
||||
let text = String::deserialize(reader)?;
|
||||
parse_duration(&text)
|
||||
.ok_or_else(|| D::Error::custom(format!("'{text}' isn't a duration: {DURATION_HELP}")))
|
||||
}
|
||||
|
||||
/// A size up to `MAX_ATTACHMENT_SIZE`.
|
||||
pub(crate) fn size<'de, D: Deserializer<'de>>(reader: D) -> Result<u64, D::Error> {
|
||||
let value = toml::Value::deserialize(reader)?;
|
||||
parse_size(&value).ok_or_else(|| {
|
||||
D::Error::custom(format!(
|
||||
"{value} isn't a size up to 1T: bytes, or a number with K, M, G or T, like \"500M\" \
|
||||
(0: no attachments)"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// An address and a port to listen on.
|
||||
pub(crate) fn listen<'de, D: Deserializer<'de>>(reader: D) -> Result<SocketAddr, D::Error> {
|
||||
let text = String::deserialize(reader)?;
|
||||
text.parse().map_err(|_| {
|
||||
D::Error::custom(format!(
|
||||
"'{text}' isn't an address and a port, like \"0.0.0.0:7000\""
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// Peer addresses, none twice.
|
||||
pub(crate) fn peers<'de, D: Deserializer<'de>>(reader: D) -> Result<Vec<String>, D::Error> {
|
||||
let peers = Vec::<String>::deserialize(reader)?;
|
||||
for (at, peer) in peers.iter().enumerate() {
|
||||
if !is_peer_address(peer) {
|
||||
return Err(D::Error::custom(format!(
|
||||
"'{peer}' isn't a host and a port, like \"10.0.0.2:7000\" or \
|
||||
\"server-2.lan:7000\""
|
||||
)));
|
||||
}
|
||||
if peers[..at].contains(peer) {
|
||||
return Err(D::Error::custom(format!("'{peer}' is given twice")));
|
||||
}
|
||||
}
|
||||
Ok(peers)
|
||||
}
|
||||
|
||||
/// Hosts without a port: IP addresses or hostnames, or `*` for all; none
|
||||
/// twice.
|
||||
pub(crate) fn hosts<'de, D: Deserializer<'de>>(reader: D) -> Result<Vec<String>, D::Error> {
|
||||
let hosts = Vec::<String>::deserialize(reader)?;
|
||||
for (at, host) in hosts.iter().enumerate() {
|
||||
if host != "*" && !is_hostname(host) && host.parse::<Ipv6Addr>().is_err() {
|
||||
return Err(D::Error::custom(format!(
|
||||
"'{host}' isn't an IP address or a hostname (without a port), like \
|
||||
\"10.0.0.2\" or \"server-2.lan\", or \"*\" for all"
|
||||
)));
|
||||
}
|
||||
if hosts[..at]
|
||||
.iter()
|
||||
.any(|before| before.eq_ignore_ascii_case(host))
|
||||
{
|
||||
return Err(D::Error::custom(format!("'{host}' is given twice")));
|
||||
}
|
||||
}
|
||||
Ok(hosts)
|
||||
}
|
||||
|
||||
/// A batch size, 1 to `MAX_MESSAGES_PER_PACKET`.
|
||||
pub(crate) fn batch_size<'de, D: Deserializer<'de>>(reader: D) -> Result<u32, D::Error> {
|
||||
let size = u32::deserialize(reader)?;
|
||||
if !(1..=MAX_MESSAGES_PER_PACKET).contains(&size) {
|
||||
return Err(D::Error::custom(format!(
|
||||
"the batch size must be 1 to {MAX_MESSAGES_PER_PACKET}"
|
||||
)));
|
||||
}
|
||||
Ok(size)
|
||||
}
|
||||
|
||||
/// Topic names (no patterns), none twice.
|
||||
pub(crate) fn topic_names<'de, D: Deserializer<'de>>(reader: D) -> Result<Vec<String>, D::Error> {
|
||||
let names = Vec::<String>::deserialize(reader)?;
|
||||
check_names(&names, false).map_err(D::Error::custom)?;
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
/// Checks a list of names (`patterns`: or patterns), none twice.
|
||||
pub(crate) fn check_names(list: &[String], patterns: bool) -> Result<(), String> {
|
||||
for (at, entry) in list.iter().enumerate() {
|
||||
let (valid, what) = if patterns {
|
||||
(is_valid_name_or_pattern(entry), "a name or a pattern")
|
||||
} else {
|
||||
(is_valid_name(entry), "a name")
|
||||
};
|
||||
if !valid {
|
||||
return Err(format!("'{entry}' isn't {what} ({NAME_HELP})"));
|
||||
}
|
||||
if list[..at].iter().any(|before| names_equal(before, entry)) {
|
||||
return Err(format!("'{entry}' is given twice"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn durations() {
|
||||
let s = Duration::from_secs;
|
||||
assert_eq!(parse_duration("30s"), Some(s(30)));
|
||||
assert_eq!(parse_duration("1d12h"), Some(s(129_600)));
|
||||
assert_eq!(parse_duration(" 2W "), Some(s(1_209_600)));
|
||||
assert_eq!(parse_duration("1m30s"), Some(s(90)));
|
||||
for bad in [
|
||||
"",
|
||||
"30",
|
||||
"s",
|
||||
"1x",
|
||||
"0s",
|
||||
"1h 30m",
|
||||
"-1s",
|
||||
"99999999999999999999w",
|
||||
] {
|
||||
assert_eq!(parse_duration(bad), None, "{bad}");
|
||||
}
|
||||
assert_eq!(parse_age("Forever"), Some(None));
|
||||
assert_eq!(parse_age("30d"), Some(Some(s(2_592_000))));
|
||||
assert_eq!(parse_age("never"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sizes() {
|
||||
let text = |t: &str| parse_size(&toml::Value::String(t.into()));
|
||||
assert_eq!(text("0"), Some(0));
|
||||
assert_eq!(text("500"), Some(500));
|
||||
assert_eq!(text("500k"), Some(500 << 10));
|
||||
assert_eq!(text("1G"), Some(1 << 30));
|
||||
assert_eq!(text("1T"), Some(1 << 40));
|
||||
assert_eq!(parse_size(&toml::Value::Integer(1024)), Some(1024));
|
||||
for bad in ["", "G", "2T", "1.5G", "1GB", "-1", "1 G"] {
|
||||
assert_eq!(text(bad), None, "{bad}");
|
||||
}
|
||||
assert_eq!(parse_size(&toml::Value::Integer(-1)), None);
|
||||
assert_eq!(parse_size(&toml::Value::Boolean(true)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_addresses() {
|
||||
for good in [
|
||||
"10.0.0.2:7000",
|
||||
"server-2.lan:7000",
|
||||
"[fd00::2]:7000",
|
||||
"localhost:1",
|
||||
] {
|
||||
assert!(is_peer_address(good), "{good}");
|
||||
}
|
||||
for bad in [
|
||||
"10.0.0.2",
|
||||
"10.0.0.2:0",
|
||||
":7000",
|
||||
"fd00::2:7000",
|
||||
"a b:7000",
|
||||
"x:70000",
|
||||
] {
|
||||
assert!(!is_peer_address(bad), "{bad}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user