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)
| 1040 | /// |
| 1041 | /// Returns `AgentError::SessionSaveFailed` if the write or rename fails. |
| 1042 | pub fn save(&self, session: &AgentSession) -> AgentResult<()> { |
| 1043 | validate_session_id(&session.session_id)?; |
| 1044 | |
| 1045 | let path = self.session_path(&session.session_id); |
| 1046 | let tmp_path = self.temp_session_path(&session.session_id); |
| 1047 | |
| 1048 | let data = |
| 1049 | serde_json::to_string_pretty(session).map_err(|e| AgentError::SessionSaveFailed { |
| 1050 | session_id: session.session_id.clone(), |
| 1051 | reason: format!("JSON serialize error: {}", e), |
| 1052 | })?; |
| 1053 | |
| 1054 | // Each writer needs its own same-directory temp file. Concurrent hook |
| 1055 | // processes can save the same session, and threads within one process |
| 1056 | // must not collide either. |
| 1057 | if let Err(e) = std::fs::write(&tmp_path, data.as_bytes()) { |
| 1058 | let _ = std::fs::remove_file(&tmp_path); |
| 1059 | return Err(AgentError::SessionSaveFailed { |
| 1060 | session_id: session.session_id.clone(), |
| 1061 | reason: format!("write temp file: {}", e), |
| 1062 | }); |
| 1063 | } |
| 1064 | |
| 1065 | // Atomic rename |
| 1066 | if let Err(e) = std::fs::rename(&tmp_path, &path) { |
| 1067 | let _ = std::fs::remove_file(&tmp_path); |
| 1068 | return Err(AgentError::SessionSaveFailed { |
| 1069 | session_id: session.session_id.clone(), |
| 1070 | reason: format!("rename temp file: {}", e), |
| 1071 | }); |
| 1072 | } |
| 1073 | |
| 1074 | Ok(()) |
| 1075 | } |
| 1076 | |
| 1077 | /// Delete a session state file. |
| 1078 | /// |