use core::fmt;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use printobserver_supervisor_api::{SessionPhase, SupervisionSession, SupervisorError};
use printobserver_types::{PrintId, 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,
#[serde(rename = "2")]
V2,
#[serde(rename = "3")]
V3,
}
const LEDGER_FORMAT: LedgerFormat = LedgerFormat::V3;
#[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}")
})
}
pub fn probe(name: &str) -> Result<Self, SupervisorError> {
if name.trim().is_empty() {
return Err(SupervisorError::Unavailable {
detail: "a probe's session name that is empty names no conversation".to_owned(),
});
}
Ok(Self(format!("probe-{name}")))
}
#[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, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CallUsage {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub input_tokens: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub output_tokens: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cache_read_tokens: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cache_write_tokens: Option<u64>,
}
impl CallUsage {
#[must_use]
pub fn conversation_tokens(&self) -> Option<u64> {
let counts = [
self.input_tokens,
self.cache_read_tokens,
self.cache_write_tokens,
self.output_tokens,
];
counts.iter().any(Option::is_some).then(|| {
counts
.iter()
.flatten()
.fold(0_u64, |sum, count| sum.saturating_add(*count))
})
}
#[must_use]
pub const fn of(usage: &oneharness_core::domain::signals::Usage) -> Self {
Self {
input_tokens: usage.input_tokens,
output_tokens: usage.output_tokens,
cache_read_tokens: usage.cache_read_tokens,
cache_write_tokens: usage.cache_write_tokens,
}
}
}
#[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 started_at: Option<Timestamp>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub failure: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub calls: Vec<CallUsage>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CompactionEnd {
Completed,
Cancelled,
Unsupported,
Failed,
}
impl CompactionEnd {
#[must_use]
pub const fn of(status: oneharness_core::domain::compact::CompactStatus) -> Self {
use oneharness_core::domain::compact::CompactStatus;
match status {
CompactStatus::Completed => Self::Completed,
CompactStatus::Cancelled => Self::Cancelled,
CompactStatus::Unsupported => Self::Unsupported,
CompactStatus::Failed => Self::Failed,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RecordedCompaction {
pub session_name: SessionName,
pub started_at: Timestamp,
pub ended_at: Timestamp,
pub ended: CompactionEnd,
pub size_before: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reported_before: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reported_after: Option<u64>,
#[serde(default)]
pub usage: CallUsage,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scheduled_check_waited_ms: Option<u64>,
}
#[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>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
compactions: Vec<RecordedCompaction>,
}
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(Self {
schema_version: LEDGER_FORMAT,
..ledger
})
}
Err(error) if error.kind() == io::ErrorKind::NotFound => {
let directory = state_dir.join(SESSIONS_DIRECTORY);
if fs::metadata(&directory).is_ok_and(|found| !found.is_dir()) {
return Err(io::Error::other(format!(
"{} is something other than a directory, so no ledger can be read from it",
directory.display()
)));
}
Ok(Self {
schema_version: LEDGER_FORMAT,
print_id: *print_id,
sessions: Vec::new(),
turns: Vec::new(),
compactions: 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
));
}
}
let opened = |name: &SessionName| {
self.sessions
.iter()
.any(|session| session.session_name == name.as_str())
};
for turn in &self.turns {
if !opened(&turn.session_name) {
return Err(format!(
"a turn is recorded against session `{}`, which this print has never opened",
turn.session_name
));
}
}
for compaction in &self.compactions {
if !opened(&compaction.session_name) {
return Err(format!(
"a compaction is recorded against session `{}`, which this print has never opened",
compaction.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)?;
let mut written = path.clone().into_os_string();
written.push(".writing");
let written = PathBuf::from(written);
fs::write(&written, text)?;
fs::rename(&written, &path)
}
pub(crate) fn sessions(&self) -> &[SupervisionSession] {
&self.sessions
}
pub(crate) fn turns(&self) -> &[RecordedTurn] {
&self.turns
}
pub(crate) fn compactions(&self) -> &[RecordedCompaction] {
&self.compactions
}
pub(crate) fn record_compaction(&mut self, compaction: RecordedCompaction) {
self.compactions.push(compaction);
}
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,
(started_at, at): (Timestamp, Timestamp),
failure: Option<&str>,
calls: Vec<CallUsage>,
) {
self.turns.push(RecordedTurn {
session_name: session_name.clone(),
ran_at: at,
started_at: Some(started_at),
failure: failure.map(ToOwned::to_owned),
calls,
});
}
}