json_state 0.1.0

A simple Rust library for managing states using json with file persistence.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
/// State management module for persisting application state in memory and on disk.
/// 
/// This module provides functionality to create, store, retrieve, and delete
/// application states using both in-memory storage and filesystem persistence.
/// Each state has a unique identifier and can store arbitrary JSON data.
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::fs::{self, File};
use std::io::{self, Write};
use std::path::Path;
use uuid::Uuid;

/// Represents a single state with a unique identifier and JSON payload.
///
/// Each `State` instance contains:
/// - A UUID that uniquely identifies the state
/// - A JSON value that represents the state's data
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct State {
    /// Unique identifier for the state
    id: Uuid,
    /// JSON data payload containing the state information
    payload: Value,
}

impl State {
    /// Creates a new state with the provided JSON payload and a randomly generated UUID.
    ///
    /// # Arguments
    ///
    /// * `payload` - A JSON value containing the state data
    ///
    /// # Returns
    ///
    /// A new `State` instance with a unique ID and the specified payload
    ///
    /// # Examples
    ///
    /// ```
    /// use serde_json::json;
    /// use state::State;
    ///
    /// let state = State::new(json!({
    ///     "name": "John",
    ///     "age": 30,
    ///     "settings": {
    ///         "theme": "dark",
    ///         "notifications": true
    ///     }
    /// }));
    /// ```
    pub fn new(payload: Value) -> Self {
        State {
            id: Uuid::new_v4(),
            payload,
        }
    }

    /// Returns a reference to the state's unique identifier.
    ///
    /// # Returns
    ///
    /// A reference to the UUID that identifies this state
    ///
    /// # Examples
    ///
    /// ```
    /// use serde_json::json;
    /// use state::State;
    ///
    /// let state = State::new(json!({"name": "John"}));
    /// let id = state.get_id();
    /// println!("State ID: {}", id);
    /// ```
    pub fn get_id(&self) -> &Uuid {
        &self.id
    }
    
    /// Returns a reference to the state's payload.
    ///
    /// # Returns
    ///
    /// A reference to the JSON value containing the state data
    ///
    /// # Examples
    ///
    /// ```
    /// use serde_json::json;
    /// use state::State;
    ///
    /// let state = State::new(json!({"name": "John"}));
    /// let payload = state.get_payload();
    /// println!("Name: {}", payload["name"]);
    /// ```
    pub fn get_payload(&self) -> &Value {
        &self.payload
    }
}

/// Manages multiple state objects with persistence capabilities.
///
/// `StateManager` provides functionality to:
/// - Save states to both memory and filesystem
/// - Load states from memory or filesystem
/// - Delete states from both memory and filesystem
/// - Load all states from a directory
#[derive(Default)]
pub struct StateManager {
    /// Directory path where state files are stored
    pub dir: String,
    /// In-memory storage of states indexed by their UUID
    pub states: HashMap<Uuid, State>,
}

impl StateManager {
    /// Creates a new `StateManager` with the specified directory for persistence.
    ///
    /// # Arguments
    ///
    /// * `dir` - The directory path where state files will be stored
    ///
    /// # Returns
    ///
    /// A new `StateManager` instance initialized with the specified directory
    ///
    /// # Examples
    ///
    /// ```
    /// use state::StateManager;
    ///
    /// let manager = StateManager::new("states".to_string());
    /// ```
    pub fn new(dir: String) -> Self {
        StateManager {
            dir,
            states: HashMap::new(),
        }
    }

    /// Saves a state to both in-memory storage and the filesystem.
    ///
    /// # Arguments
    ///
    /// * `state` - The state to save
    ///
    /// # Returns
    ///
    /// An `io::Result` indicating success or containing an error if the filesystem operation failed
    ///
    /// # Examples
    ///
    /// ```
    /// use serde_json::json;
    /// use state::{State, StateManager};
    ///
    /// let mut manager = StateManager::new("states".to_string());
    /// let state = State::new(json!({"name": "John"}));
    /// manager.save(state).expect("Failed to save state");
    /// ```
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - The directory cannot be created
    /// - The state file cannot be written
    pub fn save(&mut self, state: State) -> io::Result<()> {
        // Save in memory (HashMap)
        self.states.insert(state.get_id().clone(), state.clone());

        // Save to file system
        self.save_to_file_system(&state)?;  // Save the specific state to the file system

        Ok(())
    }

    /// Loads a state by its ID, first checking in-memory storage then the filesystem.
    ///
    /// # Arguments
    ///
    /// * `id` - The UUID of the state to load
    ///
    /// # Returns
    ///
    /// An `io::Result` containing:
    /// - `Some(State)` if the state was found
    /// - `None` if the state was not found
    /// - An error if the filesystem operation failed
    ///
    /// # Examples
    ///
    /// ```
    /// use state::StateManager;
    ///
    /// let manager = StateManager::new("states".to_string());
    /// match manager.load(&state_id) {
    ///     Ok(Some(state)) => println!("State found: {:?}", state),
    ///     Ok(None) => println!("State not found"),
    ///     Err(e) => println!("Error loading state: {}", e),
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - The state file exists but cannot be read
    /// - The state file contains invalid JSON
    pub fn load(&self, id: &Uuid) -> io::Result<Option<State>> {
        // Check memory first
        if let Some(state) = self.states.get(id) {
            return Ok(Some(state.clone()));
        }

        // If not in memory, load from file system
        self.load_from_file_system(id)
    }

    /// Deletes a state by its ID from both in-memory storage and the filesystem.
    ///
    /// # Arguments
    ///
    /// * `id` - The UUID of the state to delete
    ///
    /// # Returns
    ///
    /// An `io::Result` indicating success or containing an error if the filesystem operation failed
    ///
    /// # Examples
    ///
    /// ```
    /// use state::StateManager;
    ///
    /// let mut manager = StateManager::new("states".to_string());
    /// manager.delete(&state_id).expect("Failed to delete state");
    /// ```
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - The state file exists but cannot be deleted
    pub fn delete(&mut self, id: &Uuid) -> io::Result<()> {
        // Remove from memory (HashMap)
        self.states.remove(id);

        // Remove from file system
        self.delete_from_file_system(id)?;

        Ok(())
    }

    /// Creates a `StateManager` by loading all state files from the specified directory.
    ///
    /// # Arguments
    ///
    /// * `dir` - The directory path to load state files from
    ///
    /// # Returns
    ///
    /// An `io::Result` containing a new `StateManager` with all states loaded from the directory
    ///
    /// # Examples
    ///
    /// ```
    /// use state::StateManager;
    ///
    /// let manager = StateManager::load_from_dir("states").expect("Failed to load states");
    /// println!("Loaded {} states", manager.states.len());
    /// ```
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - The directory cannot be read
    /// - A state file contains invalid JSON
    /// - A state file cannot be read
    pub fn load_from_dir(dir: &str) -> std::io::Result<Self> {
        let mut states = HashMap::new();

        // Create directory if it doesn't exist
        if !Path::new(dir).exists() {
            fs::create_dir_all(dir)?;  // create dir if missing
            return Ok(Self {
                dir: dir.to_string(),
                states,
            });
        }

        // Only process files with .json extension AND matching UUID pattern
        for entry in fs::read_dir(dir)? {
            let entry = entry?; 
            let path = entry.path();
            
            // Check if it's a .json file
            if path.extension().map(|e| e == "json").unwrap_or(false) {
                // Get the filename without extension
                if let Some(filename) = path.file_stem() {
                    // Try to parse the filename as UUID
                    if let Ok(id) = Uuid::parse_str(&filename.to_string_lossy()) {
                        let json = fs::read_to_string(&path)?;
                        if let Ok(state) = serde_json::from_str::<State>(&json) {
                            // Validate that the ID in the filename matches the ID in the content
                            if *state.get_id() == id {
                                states.insert(id, state);
                            }
                        }
                    }
                }
            }
        }

        Ok(Self {
            dir: dir.to_string(),
            states,
        })
    }

    /// Clears all state files from the specified directory.
    ///
    /// # Arguments
    ///
    /// * `dir` - The directory path to clear
    ///
    /// # Returns
    ///
    /// An `io::Result` indicating success or containing an error if the operation failed
    ///
    /// # Examples
    ///
    /// ```
    /// use state::StateManager;
    ///
    /// StateManager::clear_dir("states").expect("Failed to clear states directory");
    /// ```
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - The directory cannot be read or modified
    pub fn clear_dir(dir: &str) -> io::Result<()> {
        if Path::new(dir).exists() {
            fs::remove_dir_all(dir)?;
        }
        fs::create_dir_all(dir)?;
        Ok(())
    }

    /// Saves a single state to the filesystem.
    ///
    /// # Arguments
    ///
    /// * `state` - The state to save to the filesystem
    ///
    /// # Returns
    ///
    /// An `io::Result` indicating success or containing an error if the operation failed
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - The directory does not exist and cannot be created
    /// - The state file cannot be created or written
    /// - The state cannot be serialized to JSON
    fn save_to_file_system(&self, state: &State) -> io::Result<()> {
        // Ensure the directory exists
        if !Path::new(&self.dir).exists() {
            fs::create_dir_all(&self.dir)?;
        }
        
        let file_path = format!("{}/{}.json", self.dir, state.get_id());  // Save the state by ID
        let json = serde_json::to_string_pretty(state)?;  // Serialize the state
        let mut file = File::create(file_path)?;  // Create the file
        file.write_all(json.as_bytes())?;  // Write the state to the file

        Ok(())
    }

    /// Loads a state from the filesystem by its ID.
    ///
    /// # Arguments
    ///
    /// * `id` - The UUID of the state to load
    ///
    /// # Returns
    ///
    /// An `io::Result` containing:
    /// - `Some(State)` if the state file was found and loaded successfully
    /// - `None` if the state file was not found
    /// - An error if the state file exists but cannot be read or contains invalid JSON
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - The state file exists but cannot be read
    /// - The state file contains invalid JSON
    fn load_from_file_system(&self, id: &Uuid) -> std::io::Result<Option<State>> {
        let file_path = format!("{}/{}.json", self.dir, id);

        // Check if the file exists
        if Path::new(&file_path).exists() {
            let json = fs::read_to_string(&file_path)?;  // Read the file content
            let state: State = serde_json::from_str(&json)?;  // Deserialize the state
            Ok(Some(state))  // Return the state
        } else {
            Ok(None)  // If the file does not exist, return None
        }
    }

    /// Deletes a state file from the filesystem by its ID.
    ///
    /// # Arguments
    ///
    /// * `id` - The UUID of the state file to delete
    ///
    /// # Returns
    ///
    /// An `io::Result` indicating success or containing an error if the operation failed
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - The state file exists but cannot be deleted
    fn delete_from_file_system(&self, id: &Uuid) -> io::Result<()> {
        let file_path = format!("{}/{}.json", self.dir, id);
        if Path::new(&file_path).exists() {
            fs::remove_file(file_path)?;  // Remove the file
        }
        Ok(())
    }
}