Save a session to disk atomically. Writes to a temporary file first, then renames to the final path. This prevents corruption if the process is killed mid-write. # Errors Returns `AgentError::SessionSaveFailed` if the write or rename fails.
(&self, session: &AgentSession)
| 491 | /// |
| 492 | /// Returns `AgentError::SessionSaveFailed` if the write or rename fails. |
| 493 | pub fn save(&self, session: &AgentSession) -> AgentResult<()> { |
| 494 | validate_session_id(&session.session_id)?; |
| 495 | |
| 496 | let path = self.session_path(&session.session_id); |
| 497 | let tmp_path = path.with_extension("json.tmp"); |
| 498 | |
| 499 | let data = |
| 500 | serde_json::to_string_pretty(session).map_err(|e| AgentError::SessionSaveFailed { |
| 501 | session_id: session.session_id.clone(), |
| 502 | reason: format!("JSON serialize error: {}", e), |
| 503 | })?; |
| 504 | |
| 505 | // Write to temp file |
| 506 | std::fs::write(&tmp_path, data.as_bytes()).map_err(|e| AgentError::SessionSaveFailed { |
| 507 | session_id: session.session_id.clone(), |
| 508 | reason: format!("write temp file: {}", e), |
| 509 | })?; |
| 510 | |
| 511 | // Atomic rename |
| 512 | std::fs::rename(&tmp_path, &path).map_err(|e| AgentError::SessionSaveFailed { |
| 513 | session_id: session.session_id.clone(), |
| 514 | reason: format!("rename temp file: {}", e), |
| 515 | })?; |
| 516 | |
| 517 | Ok(()) |
| 518 | } |
| 519 | |
| 520 | /// Delete a session state file. |
| 521 | /// |