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)
| 519 | /// |
| 520 | /// Returns `AgentError::SessionSaveFailed` if the write or rename fails. |
| 521 | pub fn save(&self, session: &AgentSession) -> AgentResult<()> { |
| 522 | validate_session_id(&session.session_id)?; |
| 523 | |
| 524 | let path = self.session_path(&session.session_id); |
| 525 | let tmp_path = path.with_extension("json.tmp"); |
| 526 | |
| 527 | let data = |
| 528 | serde_json::to_string_pretty(session).map_err(|e| AgentError::SessionSaveFailed { |
| 529 | session_id: session.session_id.clone(), |
| 530 | reason: format!("JSON serialize error: {}", e), |
| 531 | })?; |
| 532 | |
| 533 | // Write to temp file |
| 534 | std::fs::write(&tmp_path, data.as_bytes()).map_err(|e| AgentError::SessionSaveFailed { |
| 535 | session_id: session.session_id.clone(), |
| 536 | reason: format!("write temp file: {}", e), |
| 537 | })?; |
| 538 | |
| 539 | // Atomic rename |
| 540 | std::fs::rename(&tmp_path, &path).map_err(|e| AgentError::SessionSaveFailed { |
| 541 | session_id: session.session_id.clone(), |
| 542 | reason: format!("rename temp file: {}", e), |
| 543 | })?; |
| 544 | |
| 545 | Ok(()) |
| 546 | } |
| 547 | |
| 548 | /// Delete a session state file. |
| 549 | /// |