Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 29 additions & 24 deletions clients/openframe-client/src/services/last_known_good_service.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::platform::directories::DirectoryManager;
use crate::utils::fs::{atomic_write, read_json_or_quarantine, JsonFile};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::fs;
Expand Down Expand Up @@ -46,25 +47,20 @@ impl LastKnownGoodService {
}

pub async fn load(&self) -> Result<Option<String>> {
if !self.anchor_file_path.exists() {
let anchor: JsonFile<LastKnownGood> = read_json_or_quarantine(&self.anchor_file_path)
.with_context(|| {
format!(
"Failed to read last-known-good file: {:?}",
self.anchor_file_path
)
})?;
if matches!(anchor, JsonFile::Missing) {
debug!(
"No last-known-good file found at: {}",
self.anchor_file_path.display()
);
return Ok(None);
}

let json_content = fs::read_to_string(&self.anchor_file_path).with_context(|| {
format!(
"Failed to read last-known-good file: {:?}",
self.anchor_file_path
)
})?;

let anchor: LastKnownGood = serde_json::from_str(&json_content)
.context("Failed to deserialize last-known-good from JSON")?;

Ok(Some(anchor.version))
Ok(anchor.parsed().map(|anchor| anchor.version))
}

fn copy_running_to_reserve(&self) -> Result<()> {
Expand All @@ -76,6 +72,12 @@ impl LastKnownGoodService {
temp_reserve.display()
)
})?;
// Without the flush a power loss can keep the rename but drop the data, leaving a NUL-filled reserve.
fs::OpenOptions::new()
.write(true)
.open(&temp_reserve)
.and_then(|file| file.sync_all())
.with_context(|| format!("Failed to flush temp reserve {}", temp_reserve.display()))?;
fs::rename(&temp_reserve, &self.reserve_path).with_context(|| {
format!(
"Failed to move temp reserve into place: {}",
Expand All @@ -92,16 +94,9 @@ impl LastKnownGoodService {
version: version.to_string(),
})
.context("Failed to serialize last-known-good to JSON")?;
let temp_anchor = self.anchor_file_path.with_extension("json.tmp");
fs::write(&temp_anchor, json_content).with_context(|| {
format!(
"Failed to write temp last-known-good file: {:?}",
temp_anchor
)
})?;
fs::rename(&temp_anchor, &self.anchor_file_path).with_context(|| {
atomic_write(&self.anchor_file_path, json_content).with_context(|| {
format!(
"Failed to move last-known-good file into place: {:?}",
"Failed to write last-known-good file: {:?}",
self.anchor_file_path
)
})?;
Expand All @@ -116,7 +111,13 @@ impl LastKnownGoodService {

pub async fn seed_if_missing(&self) -> Result<()> {
let running_version = env!("OPENFRAME_VERSION");
let anchor = self.load().await.unwrap_or(None);
let anchor = self.load().await.unwrap_or_else(|e| {
warn!(
"Failed to load last-known-good anchor, treating it as missing: {:#}",
e
);
None
});

match anchor {
Some(ref anchor_version) if self.reserve_path.exists() => {
Expand Down Expand Up @@ -220,3 +221,7 @@ impl LastKnownGoodService {
}
}
}

#[cfg(test)]
#[path = "last_known_good_service_tests.rs"]
mod tests;
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use super::*;
use crate::test_support::directories;
use tempfile::TempDir;

fn service_in(dir: &TempDir) -> LastKnownGoodService {
LastKnownGoodService::new(directories(dir)).unwrap()
}

#[tokio::test]
async fn load_reads_the_anchor_version() {
let dir = TempDir::new().unwrap();
let service = service_in(&dir);
std::fs::write(&service.anchor_file_path, br#"{"version":"1.5.96"}"#).unwrap();

assert_eq!(service.load().await.unwrap().as_deref(), Some("1.5.96"));
}

#[tokio::test]
async fn load_treats_a_corrupt_anchor_as_missing() {
let dir = TempDir::new().unwrap();
let service = service_in(&dir);
std::fs::write(&service.anchor_file_path, [0u8; 40]).unwrap();

assert_eq!(service.load().await.unwrap(), None);
assert!(dir
.path()
.join("secured")
.join("last_known_good.json.corrupt")
.exists());
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::models::openframe_client_info::OpenFrameClientInfo;
use crate::platform::directories::DirectoryManager;
use crate::utils::fs::{atomic_write, read_json_or_quarantine, JsonFile};
use anyhow::{Context, Result};
use std::fs;
use std::path::PathBuf;
use tracing::{debug, info};

Expand All @@ -24,26 +24,20 @@ impl OpenFrameClientInfoService {
}

pub async fn get(&self) -> Result<OpenFrameClientInfo> {
if !self.info_file_path.exists() {
debug!("OpenFrame client info file doesn't exist, returning default");
return Ok(OpenFrameClientInfo::default());
}

let json_content = fs::read_to_string(&self.info_file_path).with_context(|| {
let info = read_json_or_quarantine(&self.info_file_path).with_context(|| {
format!("Failed to read client info file: {:?}", self.info_file_path)
})?;

let info: OpenFrameClientInfo = serde_json::from_str(&json_content)
.context("Failed to deserialize OpenFrame client info from JSON")?;

Ok(info)
if matches!(info, JsonFile::Missing) {
debug!("OpenFrame client info file doesn't exist, returning default");
}
Ok(info.parsed().unwrap_or_default())
}

pub async fn save(&self, info: &OpenFrameClientInfo) -> Result<()> {
let json_content = serde_json::to_string_pretty(info)
.context("Failed to serialize OpenFrame client info to JSON")?;

fs::write(&self.info_file_path, json_content).with_context(|| {
atomic_write(&self.info_file_path, json_content).with_context(|| {
format!(
"Failed to write client info file: {:?}",
self.info_file_path
Expand Down Expand Up @@ -103,3 +97,7 @@ impl OpenFrameClientInfoService {
Ok(())
}
}

#[cfg(test)]
#[path = "openframe_client_info_service_tests.rs"]
mod tests;
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
use super::*;
use crate::test_support::directories;
use tempfile::TempDir;

fn service_in(dir: &TempDir) -> OpenFrameClientInfoService {
OpenFrameClientInfoService::new(directories(dir)).unwrap()
}

fn write_info(dir: &TempDir, contents: &[u8]) {
std::fs::write(
dir.path()
.join("secured")
.join("openframe_client_info.json"),
contents,
)
.unwrap();
}

#[tokio::test]
async fn get_returns_default_for_a_corrupt_file() {
let dir = TempDir::new().unwrap();
let service = service_in(&dir);
write_info(&dir, &[0u8; 200]);

let info = service.get().await.unwrap();

assert_eq!(info.current_version, "");
assert!(dir
.path()
.join("secured")
.join("openframe_client_info.json.corrupt")
.exists());
}

#[tokio::test]
async fn reconcile_rewrites_a_corrupt_file_with_the_running_version() {
let dir = TempDir::new().unwrap();
let service = service_in(&dir);
write_info(&dir, b"");

service.reconcile_version("1.5.96").await.unwrap();

assert_eq!(service.get().await.unwrap().current_version, "1.5.96");
}

#[tokio::test]
async fn set_update_status_works_over_a_corrupt_file() {
let dir = TempDir::new().unwrap();
let service = service_in(&dir);
write_info(&dir, &[0u8; 200]);

service
.set_update_status(
crate::models::openframe_client_info::ClientUpdateStatus::Updating,
Some("1.5.99".to_string()),
)
.await
.unwrap();

let info = service.get().await.unwrap();
assert_eq!(info.target_version.as_deref(), Some("1.5.99"));
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use crate::services::tool_ops::ToolOps;
use crate::services::tool_run_manager::ToolRunManager;
use crate::services::update_handler_service::UpdateHandlerService;
use crate::services::update_state_service::UpdateStateService;
use crate::utils::fs::JsonFile;
use crate::utils::version_comparator;
use anyhow::{anyhow, Context, Result};
use semver::Version;
Expand Down Expand Up @@ -413,15 +414,16 @@ impl OpenFrameClientUpdateService {
}
}

let mut state = match self.update_state_service.load().await {
Ok(Some(state)) => state,
Ok(None) => {
let mut state = match self.update_state_service.read_state().await {
Ok(JsonFile::Parsed(state)) => state,
Ok(JsonFile::Missing) => {
warn!(
"Updater for {} exited early and the update state is gone (client uninstalled?), nothing to finish",
target_version
);
return;
}
Ok(JsonFile::Corrupt) => UpdateState::new(target_version.to_string()),
Err(e) => {
warn!(
"Updater for {} exited early and the update state is unreadable: {:#}",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -326,20 +326,22 @@ impl ToolConnectionProcessingManager {
continue;
}

if let Err(e) = tool_connection_service
// The publish already landed and nothing reads the local record, so a failed save keeps the normal cadence.
match tool_connection_service
.save(ToolConnection {
tool_agent_id: tool.tool_agent_id.clone(),
agent_tool_id: agent_tool_id.clone(),
published: true,
})
.await
{
error!(tool_id = %tool.tool_id, error = %e, "Failed to save tool connection record");
sleep(Duration::from_secs(RETRY_DELAY_SECONDS)).await;
continue;
Ok(()) => {
info!(tool_id = %tool.tool_id, agent_tool_id = %agent_tool_id, "Tool connection message published successfully and saved")
}
Err(e) => {
error!(tool_id = %tool.tool_id, agent_tool_id = %agent_tool_id, "Tool connection message published, but saving the local record failed: {e:#}")
}
}

info!(tool_id = %tool.tool_id, agent_tool_id = %agent_tool_id, "Tool connection message published successfully and saved");
reap_orphaned_helpers(&tool, &params_processor.directory_manager).await;
tokio::select! {
_ = sleep(Duration::from_secs(REPUBLISH_INTERVAL_SECONDS)) => {}
Expand Down
17 changes: 8 additions & 9 deletions clients/openframe-client/src/services/tool_connection_service.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use anyhow::{Context, Result};
use std::fs;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::Mutex;

use crate::models::tool_connection::ToolConnection;
use crate::platform::directories::DirectoryManager;
use crate::utils::fs::{atomic_write, read_json_or_quarantine};

#[derive(Clone)]
pub struct ToolConnectionService {
Expand Down Expand Up @@ -46,15 +46,10 @@ impl ToolConnectionService {
}

pub async fn get_all(&self) -> Result<Vec<ToolConnection>> {
if !self.file_path.exists() {
return Ok(Vec::new());
}
let json = fs::read_to_string(&self.file_path).with_context(|| {
let list = read_json_or_quarantine(&self.file_path).with_context(|| {
format!("Failed to read tool connections file: {:?}", self.file_path)
})?;
let list: Vec<ToolConnection> = serde_json::from_str(&json)
.context("Failed to deserialize tool connections from JSON")?;
Ok(list)
Ok(list.parsed().unwrap_or_default())
}

/// Delete a tool connection by its tool_agent_id
Expand All @@ -75,7 +70,7 @@ impl ToolConnectionService {
async fn persist(&self, list: &[ToolConnection]) -> Result<()> {
let json = serde_json::to_string_pretty(list)
.context("Failed to serialize tool connections to JSON")?;
fs::write(&self.file_path, json).with_context(|| {
atomic_write(&self.file_path, json).with_context(|| {
format!(
"Failed to write tool connections file: {:?}",
self.file_path
Expand All @@ -84,3 +79,7 @@ impl ToolConnectionService {
Ok(())
}
}

#[cfg(test)]
#[path = "tool_connection_service_tests.rs"]
mod tests;
Loading
Loading