use core::fmt;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use printobserver_types::{PrintId, SessionPhase, SupervisionSession, Timestamp};
use serde::{Deserialize, Serialize};
pub const SESSIONS_DIRECTORY: &str = "supervisor-sessions";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum LedgerFormat {
#[serde(rename = "1")]
V1,
}
const LEDGER_FORMAT: LedgerFormat = LedgerFormat::V1;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(transparent)]
pub struct SessionName(String);
impl SessionName {
#[must_use]
pub fn of(print_id: &PrintId, sequence: usize) -> Self {
Self(if sequence <= 1 {
format!("print-{print_id}")
} else {
format!("print-{print_id}-{sequence}")
})
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for SessionName {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
impl<'de> Deserialize<'de> for SessionName {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = String::deserialize(deserializer)?;
if text.trim().is_empty() {
return Err(serde::de::Error::custom(
"a session name that is empty names no conversation",
));
}
Ok(Self(text))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RecordedTurn {
pub session_name: SessionName,
pub ran_at: Timestamp,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub failure: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct PrintLedger {
schema_version: LedgerFormat,
print_id: PrintId,
sessions: Vec<SupervisionSession>,
turns: Vec<RecordedTurn>,
}
impl PrintLedger {
pub(crate) fn path(state_dir: &Path, print_id: &PrintId) -> PathBuf {
state_dir
.join(SESSIONS_DIRECTORY)
.join(format!("{print_id}.json"))
}
pub(crate) fn read(state_dir: &Path, print_id: &PrintId) -> io::Result<Self> {
let path = Self::path(state_dir, print_id);
match fs::read_to_string(&path) {
Ok(text) => {
let ledger: Self = serde_json::from_str(&text).map_err(|error| {
io::Error::other(format!(
"{} is not a ledger this build reads (it writes {LEDGER_FORMAT:?}): {error}",
path.display()
))
})?;
if ledger.print_id != *print_id {
return Err(io::Error::other(format!(
"{} holds the sessions of print {}, not of print {print_id}",
path.display(),
ledger.print_id
)));
}
ledger
.agrees_with_itself()
.map_err(|detail| io::Error::other(format!("{}: {detail}", path.display())))?;
Ok(ledger)
}
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(Self {
schema_version: LEDGER_FORMAT,
print_id: *print_id,
sessions: Vec::new(),
turns: Vec::new(),
}),
Err(error) => Err(error),
}
}
fn agrees_with_itself(&self) -> Result<(), String> {
for (index, session) in self.sessions.iter().enumerate() {
if session.print_id != self.print_id {
return Err(format!(
"session `{}` is of print {}, and this is the ledger of print {}",
session.session_name, session.print_id, self.print_id
));
}
let expected = SessionName::of(&self.print_id, index + 1);
if session.session_name != expected.as_str() {
return Err(format!(
"session {} of this print is named `{}`, and this build names it `{expected}`",
index + 1,
session.session_name
));
}
}
for turn in &self.turns {
if !self
.sessions
.iter()
.any(|session| session.session_name == turn.session_name.as_str())
{
return Err(format!(
"a turn is recorded against session `{}`, which this print has never opened",
turn.session_name
));
}
}
Ok(())
}
pub(crate) fn write(&self, state_dir: &Path) -> io::Result<()> {
let path = Self::path(state_dir, &self.print_id);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let text = serde_json::to_string_pretty(self).map_err(io::Error::other)?;
fs::write(path, text)
}
pub(crate) fn sessions(&self) -> &[SupervisionSession] {
&self.sessions
}
pub(crate) fn turns(&self) -> &[RecordedTurn] {
&self.turns
}
pub(crate) fn session_for_next_turn(&self) -> SessionName {
match self.sessions.last() {
Some(session) if session.closed_at.is_none() => {
SessionName(session.session_name.clone())
}
_ => SessionName::of(&self.print_id, self.sessions.len() + 1),
}
}
pub(crate) fn name_after_current(&self) -> SessionName {
SessionName::of(&self.print_id, self.sessions.len() + 1)
}
pub(crate) fn close_current(
&mut self,
reason: &str,
at: Timestamp,
) -> Option<SupervisionSession> {
let session = self
.sessions
.last_mut()
.filter(|session| session.closed_at.is_none())?;
session.closed_at = Some(at);
session.close_reason = Some(reason.to_owned());
Some(session.clone())
}
pub(crate) fn record_session(
&mut self,
name: &SessionName,
harness_identity: &str,
phase: SessionPhase,
at: Timestamp,
) -> SupervisionSession {
let known = self.sessions.iter().rposition(|session| {
session.session_name == name.as_str() && session.closed_at.is_none()
});
if let Some(index) = known {
let session = &mut self.sessions[index];
if phase == SessionPhase::Created {
session.created_at = at;
}
session.last_turn_at = at;
harness_identity.clone_into(&mut session.harness_identity);
return session.clone();
}
let session = SupervisionSession {
print_id: self.print_id,
session_name: name.to_string(),
harness_identity: harness_identity.to_owned(),
created_at: at,
last_turn_at: at,
closed_at: None,
close_reason: None,
};
self.sessions.push(session.clone());
session
}
pub(crate) fn record_turn(
&mut self,
session_name: &SessionName,
at: Timestamp,
failure: Option<&str>,
) {
self.turns.push(RecordedTurn {
session_name: session_name.clone(),
ran_at: at,
failure: failure.map(ToOwned::to_owned),
});
}
}