use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use printobserver_octoprint::{FanSupport, OctoPrintConfig};
use printobserver_oneharness::{HarnessIdentity, ModelName};
use printobserver_types::SafetyEnvelope;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
pub const DEFAULT_INGRESS_ANSWER_BOUND_MS: u64 = 1_000;
pub const OBICO_POSTING_TIMEOUT_MS: u64 = 5_000;
pub const ASSETS_DIRECTORY: &str = "assets";
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ConfigField {
StateDir,
Listen,
OctoprintUrl,
OctoprintApiKey,
OctoprintFan,
SafetyEnvelope,
Harness,
Model,
SkillPath,
PromptTemplatePath,
IngressAnswerBoundMs,
IngressSharedSecret,
}
impl ConfigField {
pub const ALL: [Self; 12] = [
Self::StateDir,
Self::Listen,
Self::OctoprintUrl,
Self::OctoprintApiKey,
Self::OctoprintFan,
Self::SafetyEnvelope,
Self::Harness,
Self::Model,
Self::SkillPath,
Self::PromptTemplatePath,
Self::IngressAnswerBoundMs,
Self::IngressSharedSecret,
];
#[must_use]
pub const fn key(self) -> &'static str {
match self {
Self::StateDir => "state_dir",
Self::Listen => "listen",
Self::OctoprintUrl => "octoprint.url",
Self::OctoprintApiKey => "octoprint.api_key",
Self::OctoprintFan => "octoprint.fan",
Self::SafetyEnvelope => "safety",
Self::Harness => "supervisor.harness",
Self::Model => "supervisor.model",
Self::SkillPath => "supervisor.skill_path",
Self::PromptTemplatePath => "supervisor.prompt_template_path",
Self::IngressAnswerBoundMs => "ingress.answer_bound_ms",
Self::IngressSharedSecret => "ingress.shared_secret",
}
}
}
impl core::fmt::Display for ConfigField {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter.write_str(self.key())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigError {
Unreadable {
path: PathBuf,
detail: String,
},
Unparsable {
path: PathBuf,
detail: String,
},
Field {
field: ConfigField,
detail: String,
},
}
impl ConfigError {
#[must_use]
pub const fn field(&self) -> Option<ConfigField> {
match self {
Self::Field { field, .. } => Some(*field),
_ => None,
}
}
pub(crate) fn about(field: ConfigField, detail: impl Into<String>) -> Self {
Self::Field {
field,
detail: detail.into(),
}
}
}
impl core::fmt::Display for ConfigError {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Unreadable { path, detail } => write!(
formatter,
"the configuration file {} could not be read: {detail}",
path.display()
),
Self::Unparsable { path, detail } => write!(
formatter,
"the configuration file {} could not be read as this program's \
configuration: {detail}",
path.display()
),
Self::Field { field, detail } => write!(
formatter,
"the configuration field `{field}` cannot be accepted: {detail}"
),
}
}
}
impl core::error::Error for ConfigError {}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(
crate = "printobserver_types::serde",
deny_unknown_fields,
rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct OctoprintSection {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub api_key: Option<String>,
#[serde(default = "commandable")]
pub fan: String,
}
pub const FAN_VOCABULARY: [(&str, FanSupport); 2] = [
("commandable", FanSupport::Commandable),
("absent", FanSupport::Absent),
];
fn commandable() -> String {
FAN_VOCABULARY[0].0.to_owned()
}
impl Default for OctoprintSection {
fn default() -> Self {
Self {
url: None,
api_key: None,
fan: commandable(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(
crate = "printobserver_types::serde",
deny_unknown_fields,
rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
#[derive(Default)]
pub struct SupervisorSection {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub harness: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub model: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub skill_path: Option<PathBuf>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub prompt_template_path: Option<PathBuf>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(
crate = "printobserver_types::serde",
deny_unknown_fields,
rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct IngressSection {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub shared_secret: Option<String>,
#[serde(default = "default_answer_bound_ms")]
pub answer_bound_ms: u64,
}
const fn default_answer_bound_ms() -> u64 {
DEFAULT_INGRESS_ANSWER_BOUND_MS
}
impl Default for IngressSection {
fn default() -> Self {
Self {
shared_secret: None,
answer_bound_ms: DEFAULT_INGRESS_ANSWER_BOUND_MS,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(
crate = "printobserver_types::serde",
deny_unknown_fields,
rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct ConfigFile {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state_dir: Option<PathBuf>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub listen: Option<String>,
#[serde(default)]
pub octoprint: OctoprintSection,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub safety: Option<SafetyEnvelope>,
#[serde(default)]
pub supervisor: SupervisorSection,
#[serde(default)]
pub ingress: IngressSection,
}
#[derive(Clone, PartialEq, Eq)]
pub struct SharedSecret(String);
pub const REDACTED: &str = "<redacted>";
impl SharedSecret {
pub fn new(value: &str) -> Result<Self, ConfigError> {
if value.trim().is_empty() {
return Err(ConfigError::about(
ConfigField::IngressSharedSecret,
"it is empty, and anything that can post to the ingress can pause a printer",
));
}
Ok(Self(value.to_owned()))
}
#[must_use]
pub fn matches(&self, offered: Option<&str>) -> bool {
let Some(offered) = offered else {
return false;
};
let expected = self.0.as_bytes();
let mut difference = expected.len() ^ offered.len();
for (index, byte) in offered.bytes().enumerate() {
let against = expected[index % expected.len().max(1)];
difference |= usize::from(byte ^ against);
}
difference == 0
}
}
impl core::fmt::Display for SharedSecret {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter.write_str(REDACTED)
}
}
impl core::fmt::Debug for SharedSecret {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(formatter, "SharedSecret({REDACTED})")
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ServerConfig {
pub state_dir: PathBuf,
pub listen: SocketAddr,
pub octoprint: OctoPrintConfig,
pub safety: SafetyEnvelope,
pub harness: HarnessIdentity,
pub model: Option<ModelName>,
pub skill_path: Option<PathBuf>,
pub prompt_template_path: Option<PathBuf>,
pub ingress_answer_bound: core::time::Duration,
pub ingress_shared_secret: SharedSecret,
}
impl ServerConfig {
pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
let path = path.as_ref();
let text = std::fs::read_to_string(path).map_err(|error| ConfigError::Unreadable {
path: path.to_path_buf(),
detail: error.to_string(),
})?;
Self::parse(&text, path)
}
pub fn parse(text: &str, path: &Path) -> Result<Self, ConfigError> {
let file: ConfigFile = toml::from_str(text).map_err(|error| ConfigError::Unparsable {
path: path.to_path_buf(),
detail: error.to_string(),
})?;
Self::validate(file)
}
fn validate(file: ConfigFile) -> Result<Self, ConfigError> {
let state_dir =
state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?;
let listen = listen_address(&required(ConfigField::Listen, file.listen)?)?;
let octoprint = octoprint(&file.octoprint)?;
let safety = required(ConfigField::SafetyEnvelope, file.safety)?;
check_envelope(&safety)?;
let harness = HarnessIdentity::new(&named(ConfigField::Harness, file.supervisor.harness)?)
.map_err(|error| ConfigError::about(ConfigField::Harness, error.to_string()))?;
let model = match file.supervisor.model {
None => None,
Some(name) => Some(
ModelName::new(&named(ConfigField::Model, Some(name))?)
.map_err(|error| ConfigError::about(ConfigField::Model, error.to_string()))?,
),
};
let skill_path = readable(
ConfigField::SkillPath,
file.supervisor.skill_path.as_deref(),
)?;
let prompt_template_path = readable(
ConfigField::PromptTemplatePath,
file.supervisor.prompt_template_path.as_deref(),
)?;
let ingress_answer_bound = answer_bound(file.ingress.answer_bound_ms)?;
let ingress_shared_secret = SharedSecret::new(&required(
ConfigField::IngressSharedSecret,
file.ingress.shared_secret,
)?)?;
Ok(Self {
state_dir,
listen,
octoprint,
safety,
harness,
model,
skill_path,
prompt_template_path,
ingress_answer_bound,
ingress_shared_secret,
})
}
#[must_use]
pub fn assets_dir(&self) -> PathBuf {
self.state_dir.join(ASSETS_DIRECTORY)
}
}
fn required<T>(field: ConfigField, value: Option<T>) -> Result<T, ConfigError> {
value.ok_or_else(|| ConfigError::about(field, "the configuration file carries no value for it"))
}
fn named(field: ConfigField, value: Option<String>) -> Result<String, ConfigError> {
let value = required(field, value)?;
if value.trim().is_empty() {
return Err(ConfigError::about(
field,
"it is empty, and an empty value names nothing",
));
}
Ok(value.trim().to_owned())
}
fn state_directory(named: &Path) -> Result<PathBuf, ConfigError> {
if named.as_os_str().is_empty() {
return Err(ConfigError::about(
ConfigField::StateDir,
"it names no directory, and this server's whole state lives in one",
));
}
std::fs::create_dir_all(named).map_err(|error| {
ConfigError::about(
ConfigField::StateDir,
format!("{} cannot be created: {error}", named.display()),
)
})?;
named.canonicalize().map_err(|error| {
ConfigError::about(
ConfigField::StateDir,
format!("{} cannot be resolved: {error}", named.display()),
)
})
}
fn listen_address(named: &str) -> Result<SocketAddr, ConfigError> {
named.trim().parse().map_err(|error| {
ConfigError::about(
ConfigField::Listen,
format!("{named:?} is no address to listen on: {error}"),
)
})
}
fn octoprint(section: &OctoprintSection) -> Result<OctoPrintConfig, ConfigError> {
let fan = fan_support(§ion.fan)?;
let url = named(ConfigField::OctoprintUrl, section.url.clone())?;
let key = named(ConfigField::OctoprintApiKey, section.api_key.clone())?;
OctoPrintConfig::new(&url, key)
.map(|configured| configured.with_fan(fan))
.map_err(|error| {
let field = match error {
printobserver_octoprint::ConfigError::EmptyApiKey => ConfigField::OctoprintApiKey,
_ => ConfigField::OctoprintUrl,
};
ConfigError::about(field, error.to_string())
})
}
fn fan_support(named: &str) -> Result<FanSupport, ConfigError> {
FAN_VOCABULARY
.iter()
.find(|(spelling, _)| *spelling == named.trim())
.map(|(_, support)| *support)
.ok_or_else(|| {
let vocabulary: Vec<&str> = FAN_VOCABULARY.iter().map(|(word, _)| *word).collect();
ConfigError::about(
ConfigField::OctoprintFan,
format!("{named:?} is not one of {}", vocabulary.join(" or ")),
)
})
}
fn check_envelope(envelope: &SafetyEnvelope) -> Result<(), ConfigError> {
if envelope.allowed.is_empty() {
return Err(ConfigError::about(
ConfigField::SafetyEnvelope,
"it allows no adjustable at all, so no adjustment could ever be accepted",
));
}
for (adjustable, range) in &envelope.allowed {
if !range.min.is_finite() || !range.max.is_finite() || range.min > range.max {
return Err(ConfigError::about(
ConfigField::SafetyEnvelope,
format!(
"the range allowed for {adjustable} runs from {} to {}, which admits \
no value",
range.min, range.max
),
));
}
}
if envelope.agent_min_interval_s < 0 {
return Err(ConfigError::about(
ConfigField::SafetyEnvelope,
format!(
"the agent's minimum interval is {}s, and an interval is a count of seconds",
envelope.agent_min_interval_s
),
));
}
Ok(())
}
fn readable(field: ConfigField, named: Option<&Path>) -> Result<Option<PathBuf>, ConfigError> {
let Some(path) = named else {
return Ok(None);
};
std::fs::read_to_string(path)
.map(|_| Some(path.to_path_buf()))
.map_err(|error| {
ConfigError::about(field, format!("{} cannot be read: {error}", path.display()))
})
}
fn answer_bound(milliseconds: u64) -> Result<core::time::Duration, ConfigError> {
if milliseconds == 0 {
return Err(ConfigError::about(
ConfigField::IngressAnswerBoundMs,
"a bound of zero is an ingress that has run out of time before it starts",
));
}
if milliseconds >= OBICO_POSTING_TIMEOUT_MS {
return Err(ConfigError::about(
ConfigField::IngressAnswerBoundMs,
format!(
"{milliseconds}ms is not below the {OBICO_POSTING_TIMEOUT_MS}ms Obico posts \
under, so an alert answered at that bound is one Obico has already \
abandoned — and its posting does not retry"
),
));
}
Ok(core::time::Duration::from_millis(milliseconds))
}