Update PingPong example state recovery mechanism.

This commit is contained in:
Alejandro Cabeza Romero 2024-12-30 13:13:57 +01:00
parent 2603f23e29
commit bef6f8c5c2
No known key found for this signature in database
GPG Key ID: DA3D14AE478030FD
3 changed files with 12 additions and 16 deletions

View File

@ -1 +1 @@
{"pong_count":12}
{"pong_count":3}

View File

@ -13,6 +13,15 @@ pub struct StateSaveOperator {
#[async_trait::async_trait]
impl StateOperator for StateSaveOperator {
type StateInput = PingState;
type LoadError = std::io::Error;
fn try_load(
settings: &<Self::StateInput as ServiceState>::Settings,
) -> Result<Option<Self::StateInput>, Self::LoadError> {
let state_string = std::fs::read_to_string(&settings.state_save_path)?;
serde_json::from_str(&state_string)
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
}
fn from_settings(settings: <Self::StateInput as ServiceState>::Settings) -> Self {
Self {

View File

@ -1,5 +1,3 @@
// STD
use std::io;
// Crates
use overwatch_rs::services::state::ServiceState;
use serde::{Deserialize, Serialize};
@ -14,22 +12,11 @@ pub struct PingState {
pub pong_count: u32,
}
impl PingState {
fn load_saved_state(save_path: &str) -> io::Result<Self> {
let json_state = std::fs::read(save_path)?;
let state = serde_json::from_slice(json_state.as_slice())
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
Ok(state)
}
}
impl ServiceState for PingState {
type Settings = PingSettings;
type Error = PingStateError;
fn from_settings(settings: &Self::Settings) -> Result<Self, Self::Error> {
let state = Self::load_saved_state(settings.state_save_path.as_str())
.unwrap_or_else(|_error| Self::default());
Ok(state)
fn from_settings(_settings: &Self::Settings) -> Result<Self, Self::Error> {
Ok(Self::default())
}
}