| 1 | use anyhow::{Context, Result, anyhow}; |
| 2 | use codewhale_protocol::agent_mail::{ |
| 3 | AgentMailAddress, AgentMailEnvelope, AgentMailMessageId, MissionMailEvent, |
| 4 | }; |
| 5 | use rusqlite::{Connection, OpenFlags, OptionalExtension, TransactionBehavior, params}; |
| 6 | use std::fs; |
| 7 | use std::path::{Path, PathBuf}; |
| 8 | use std::time::Duration; |
| 9 | |
| 10 | use super::{checked_existing_runtime_store_dir, reject_symlinked_store_file}; |
| 11 | |
| 12 | #[derive(Debug, Clone)] |
| 13 | pub(super) struct AgentMailStore { |
| 14 | directory: PathBuf, |
| 15 | mission_updates: std::sync::Arc<tokio::sync::Notify>, |
| 16 | } |
| 17 | |
| 18 | impl AgentMailStore { |
| 19 | pub(super) fn new(directory: PathBuf) -> Self { |
| 20 | Self { |
| 21 | directory, |
| 22 | mission_updates: Default::default(), |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | fn database_path(&self) -> PathBuf { |
| 27 | self.directory.join("mail.sqlite3") |
| 28 | } |
| 29 | |
| 30 | fn connect(&self, create: bool) -> Result<Option<Connection>> { |
| 31 | self.connect_for(create, true) |
| 32 | } |
| 33 | |
| 34 | fn connect_for(&self, create: bool, allow_migration: bool) -> Result<Option<Connection>> { |
| 35 | let directory = checked_existing_runtime_store_dir(&self.directory)?; |
| 36 | let database = self.database_path(); |
| 37 | reject_symlinked_store_file(&database)?; |
| 38 | reject_symlinked_store_file(&database.with_file_name("mail.sqlite3-journal"))?; |
| 39 | if !create |
| 40 | && !database.try_exists()? |
| 41 | && (!allow_migration || !has_legacy_records(&directory)?) |
| 42 | { |
| 43 | return Ok(None); |
| 44 | } |
| 45 | let source = codewhale_util::files::WorkspaceFile::open( |
| 46 | &directory, |
| 47 | Path::new("mail.sqlite3"), |
| 48 | allow_migration, |
| 49 | )?; |
| 50 | match source.open_file_shared() { |
| 51 | Ok(_) => {} |
| 52 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => { |
| 53 | if !allow_migration { |
| 54 | return Ok(None); |
| 55 | } |
| 56 | source.open_update(true, false)?; |
| 57 | } |
| 58 | Err(error) => return Err(error.into()), |
| 59 | } |
| 60 | match source.sibling("mail.sqlite3-journal")?.open_file_shared() { |
| 61 | Ok(_) => {} |
| 62 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} |
| 63 | Err(error) => return Err(error.into()), |
| 64 | } |
| 65 | let access = if allow_migration { |
| 66 | OpenFlags::SQLITE_OPEN_READ_WRITE |
| 67 | } else { |
| 68 | OpenFlags::SQLITE_OPEN_READ_ONLY |
| 69 | }; |
| 70 | let mut connection = Connection::open_with_flags( |
| 71 | directory.join("mail.sqlite3"), |
| 72 | access | OpenFlags::SQLITE_OPEN_NOFOLLOW, |
| 73 | )?; |
| 74 | connection.busy_timeout(Duration::from_secs(5))?; |
| 75 | if allow_migration { |
| 76 | connection.pragma_update(None, "synchronous", "FULL")?; |
| 77 | } |
| 78 | let schema: u32 = connection.pragma_query_value(None, "user_version", |row| row.get(0))?; |
| 79 | match schema { |
| 80 | 0 | 1 if allow_migration => Self::migrate(&mut connection, &directory)?, |
| 81 | 0 | 1 => return Ok(None), |
| 82 | 2 => {} |
| 83 | _ => anyhow::bail!("Unsupported Runtime Agent Mail schema {schema}"), |
| 84 | } |
| 85 | Ok(Some(connection)) |
| 86 | } |
| 87 | |
| 88 | fn migrate(connection: &mut Connection, directory: &Path) -> Result<()> { |
| 89 | let transaction = connection.transaction_with_behavior(TransactionBehavior::Immediate)?; |
| 90 | let schema: u32 = transaction.pragma_query_value(None, "user_version", |row| row.get(0))?; |
| 91 | if schema == 2 { |
| 92 | transaction.commit()?; |
| 93 | return Ok(()); |
| 94 | } |
| 95 | anyhow::ensure!( |
| 96 | schema <= 1, |
| 97 | "Unsupported Runtime Agent Mail schema {schema}" |
| 98 | ); |
| 99 | if schema == 0 { |
| 100 | transaction.execute_batch( |
| 101 | "CREATE TABLE mail ( |
| 102 | id TEXT PRIMARY KEY, |
| 103 | owner TEXT NOT NULL, |
| 104 | workspace TEXT NOT NULL, |
| 105 | destination TEXT NOT NULL, |
| 106 | created_at TEXT NOT NULL, |
| 107 | envelope TEXT NOT NULL, |
| 108 | mission_scope TEXT |
| 109 | ); |
| 110 | CREATE INDEX mail_inbox ON mail(owner, workspace, destination, created_at, id);", |
| 111 | )?; |
| 112 | } else { |
| 113 | transaction.execute_batch("ALTER TABLE mail ADD COLUMN mission_scope TEXT;")?; |
| 114 | } |
| 115 | transaction.execute_batch( |
| 116 | "CREATE TABLE mission_mail_events ( |
| 117 | sequence INTEGER PRIMARY KEY AUTOINCREMENT, |
| 118 | mission_scope TEXT NOT NULL, |
| 119 | envelope TEXT NOT NULL |
| 120 | ); |
| 121 | CREATE INDEX mission_mail_replay ON mission_mail_events(mission_scope, sequence); |
| 122 | CREATE TRIGGER mission_mail_insert AFTER INSERT ON mail |
| 123 | WHEN NEW.mission_scope IS NOT NULL |
| 124 | BEGIN |
| 125 | INSERT INTO mission_mail_events(mission_scope, envelope) |
| 126 | VALUES (NEW.mission_scope, NEW.envelope); |
| 127 | END; |
| 128 | CREATE TRIGGER mission_mail_update AFTER UPDATE OF envelope ON mail |
| 129 | WHEN NEW.mission_scope IS NOT NULL AND NEW.envelope != OLD.envelope |
| 130 | BEGIN |
| 131 | INSERT INTO mission_mail_events(mission_scope, envelope) |
| 132 | VALUES (NEW.mission_scope, NEW.envelope); |
| 133 | END;", |
| 134 | )?; |
| 135 | if schema == 0 { |
| 136 | for entry in fs::read_dir(directory)? { |
| 137 | let path = entry?.path(); |
| 138 | if path.extension().is_none_or(|extension| extension != "json") { |
| 139 | continue; |
| 140 | } |
| 141 | use std::io::Read as _; |
| 142 | const MAX_LEGACY_MAIL_BYTES: u64 = 1024 * 1024; |
| 143 | let file = codewhale_util::fs_confined::open_read(directory, &path)?; |
| 144 | let mut raw = String::new(); |
| 145 | file.take(MAX_LEGACY_MAIL_BYTES + 1) |
| 146 | .read_to_string(&mut raw)?; |
| 147 | anyhow::ensure!( |
| 148 | raw.len() as u64 <= MAX_LEGACY_MAIL_BYTES, |
| 149 | "Legacy Agent Mail envelope is too large" |
| 150 | ); |
| 151 | let record = decode(&raw) |
| 152 | .with_context(|| format!("Import Agent Mail record {}", path.display()))?; |
| 153 | anyhow::ensure!( |
| 154 | path.file_stem().and_then(|name| name.to_str()) |
| 155 | == Some(record.message_id.as_str()), |
| 156 | "Agent Mail legacy record ID differs from its file name" |
| 157 | ); |
| 158 | Self::write(&transaction, &record, None)?; |
| 159 | } |
| 160 | } |
| 161 | transaction.pragma_update(None, "user_version", 2)?; |
| 162 | transaction.commit()?; |
| 163 | Ok(()) |
| 164 | } |
| 165 | |
| 166 | pub(super) fn save(&self, mail: &AgentMailEnvelope) -> Result<()> { |
| 167 | self.save_in_scope(mail, None) |
| 168 | } |
| 169 | |
| 170 | pub(super) fn save_in_scope( |
| 171 | &self, |
| 172 | mail: &AgentMailEnvelope, |
| 173 | mission_scope: Option<&str>, |
| 174 | ) -> Result<()> { |
| 175 | let connection = self |
| 176 | .connect(true)? |
| 177 | .context("Agent Mail database unavailable")?; |
| 178 | Self::write(&connection, mail, mission_scope)?; |
| 179 | self.mission_updates.notify_waiters(); |
| 180 | Ok(()) |
| 181 | } |
| 182 | |
| 183 | fn write( |
| 184 | connection: &Connection, |
| 185 | mail: &AgentMailEnvelope, |
| 186 | mission_scope: Option<&str>, |
| 187 | ) -> Result<()> { |
| 188 | mail.validate().map_err(|error| anyhow!(error))?; |
| 189 | let rows = connection.execute( |
| 190 | "INSERT INTO mail(id, owner, workspace, destination, created_at, envelope, mission_scope) |
| 191 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) |
| 192 | ON CONFLICT(id) DO UPDATE SET envelope = excluded.envelope |
| 193 | WHERE mail.owner = excluded.owner AND mail.workspace = excluded.workspace |
| 194 | AND mail.destination = excluded.destination AND mail.created_at = excluded.created_at |
| 195 | AND (excluded.mission_scope IS NULL OR mail.mission_scope = excluded.mission_scope)", |
| 196 | params![ |
| 197 | mail.message_id.as_str(), |
| 198 | mail.destination.owner_id, |
| 199 | mail.destination.workspace_id, |
| 200 | mail.destination.thread_id, |
| 201 | mail.created_at |
| 202 | .to_rfc3339_opts(chrono::SecondsFormat::Nanos, true), |
| 203 | serde_json::to_string(mail)?, |
| 204 | mission_scope, |
| 205 | ], |
| 206 | )?; |
| 207 | anyhow::ensure!(rows == 1, "Agent Mail envelope identity changed"); |
| 208 | Ok(()) |
| 209 | } |
| 210 | |
| 211 | pub(super) fn load(&self, id: &AgentMailMessageId) -> Result<Option<AgentMailEnvelope>> { |
| 212 | Ok(self.load_with_scope(id)?.map(|(envelope, _)| envelope)) |
| 213 | } |
| 214 | |
| 215 | pub(super) fn load_with_scope( |
| 216 | &self, |
| 217 | id: &AgentMailMessageId, |
| 218 | ) -> Result<Option<(AgentMailEnvelope, Option<String>)>> { |
| 219 | let Some(connection) = self.connect(false)? else { |
| 220 | return Ok(None); |
| 221 | }; |
| 222 | let row: Option<(String, Option<String>)> = connection |
| 223 | .query_row( |
| 224 | "SELECT envelope, mission_scope FROM mail WHERE id = ?1", |
| 225 | [id.as_str()], |
| 226 | |row| Ok((row.get(0)?, row.get(1)?)), |
| 227 | ) |
| 228 | .optional()?; |
| 229 | row.map(|(raw, scope)| Ok((decode(&raw)?, scope))) |
| 230 | .transpose() |
| 231 | } |
| 232 | |
| 233 | pub(super) fn mission_updates(&self) -> std::sync::Arc<tokio::sync::Notify> { |
| 234 | self.mission_updates.clone() |
| 235 | } |
| 236 | |
| 237 | pub(super) fn mission_events( |
| 238 | &self, |
| 239 | scope: &str, |
| 240 | owner_id: &str, |
| 241 | after: u64, |
| 242 | limit: usize, |
| 243 | ) -> Result<Vec<MissionMailEvent>> { |
| 244 | let Ok(after) = i64::try_from(after) else { |
| 245 | return Ok(Vec::new()); |
| 246 | }; |
| 247 | self.read_mission_events(scope, owner_id, after, limit, false) |
| 248 | } |
| 249 | |
| 250 | pub(super) fn recent_mission_events( |
| 251 | &self, |
| 252 | scope: &str, |
| 253 | owner_id: &str, |
| 254 | limit: usize, |
| 255 | ) -> Result<Vec<MissionMailEvent>> { |
| 256 | let mut events = self.read_mission_events(scope, owner_id, 0, limit, true)?; |
| 257 | events.reverse(); |
| 258 | Ok(events) |
| 259 | } |
| 260 | |
| 261 | fn read_mission_events( |
| 262 | &self, |
| 263 | scope: &str, |
| 264 | owner_id: &str, |
| 265 | after: i64, |
| 266 | limit: usize, |
| 267 | newest_first: bool, |
| 268 | ) -> Result<Vec<MissionMailEvent>> { |
| 269 | let limit = i64::try_from(limit).unwrap_or(i64::MAX); |
| 270 | let Some(connection) = self.connect_for(false, false)? else { |
| 271 | return Ok(Vec::new()); |
| 272 | }; |
| 273 | let order = if newest_first { "DESC" } else { "ASC" }; |
| 274 | let mut query = connection.prepare(&format!( |
| 275 | "SELECT sequence, envelope FROM mission_mail_events |
| 276 | WHERE mission_scope = ?1 AND sequence > ?2 |
| 277 | AND json_extract(envelope, '$.source.owner_id') = ?3 |
| 278 | AND json_extract(envelope, '$.destination.owner_id') = ?3 |
| 279 | ORDER BY sequence {order} LIMIT ?4" |
| 280 | ))?; |
| 281 | let rows = query.query_map(params![scope, after, owner_id, limit], |row| { |
| 282 | Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?)) |
| 283 | })?; |
| 284 | let mut events = Vec::new(); |
| 285 | for row in rows { |
| 286 | let (sequence, raw) = row?; |
| 287 | events.push(MissionMailEvent { |
| 288 | sequence: u64::try_from(sequence)?, |
| 289 | envelope: decode(&raw)?, |
| 290 | }); |
| 291 | } |
| 292 | Ok(events) |
| 293 | } |
| 294 | |
| 295 | pub(super) fn list( |
| 296 | &self, |
| 297 | address: Option<&AgentMailAddress>, |
| 298 | ) -> Result<Vec<AgentMailEnvelope>> { |
| 299 | let Some(connection) = self.connect(false)? else { |
| 300 | return Ok(Vec::new()); |
| 301 | }; |
| 302 | let mut mail = Vec::new(); |
| 303 | if let Some(address) = address { |
| 304 | let mut query = connection.prepare( |
| 305 | "SELECT envelope FROM mail WHERE owner = ?1 AND workspace = ?2 AND destination = ?3 |
| 306 | ORDER BY created_at, id", |
| 307 | )?; |
| 308 | let rows = query.query_map( |
| 309 | params![address.owner_id, address.workspace_id, address.thread_id], |
| 310 | |row| row.get::<_, String>(0), |
| 311 | )?; |
| 312 | for row in rows { |
| 313 | let envelope = decode(&row?)?; |
| 314 | if envelope.destination.matches_current_thread(address) { |
| 315 | mail.push(envelope); |
| 316 | } |
| 317 | } |
| 318 | } else { |
| 319 | let mut query = |
| 320 | connection.prepare("SELECT envelope FROM mail ORDER BY created_at, id")?; |
| 321 | for row in query.query_map([], |row| row.get::<_, String>(0))? { |
| 322 | mail.push(decode(&row?)?); |
| 323 | } |
| 324 | } |
| 325 | Ok(mail) |
| 326 | } |
| 327 | |
| 328 | pub(super) fn list_pending_wake_thread_ids(&self, owner_id: &str) -> Result<Vec<String>> { |
| 329 | let Some(connection) = self.connect_for(false, false)? else { |
| 330 | return Ok(Vec::new()); |
| 331 | }; |
| 332 | let mut query = connection.prepare( |
| 333 | "SELECT DISTINCT destination FROM mail |
| 334 | WHERE owner = ?1 |
| 335 | AND json_extract(envelope, '$.delivery_mode') = 'wake_at_safe_boundary' |
| 336 | AND json_extract(envelope, '$.trigger_turn') = 1 |
| 337 | AND ( |
| 338 | json_extract(envelope, '$.status') = 'queued' |
| 339 | OR ( |
| 340 | json_extract(envelope, '$.status') = 'failed' |
| 341 | AND json_extract(envelope, '$.failure.retryable') = 1 |
| 342 | ) |
| 343 | ) |
| 344 | ORDER BY created_at, id", |
| 345 | )?; |
| 346 | let rows = query.query_map([owner_id], |row| row.get::<_, String>(0))?; |
| 347 | let mut thread_ids = Vec::new(); |
| 348 | for row in rows { |
| 349 | thread_ids.push(row?); |
| 350 | } |
| 351 | Ok(thread_ids) |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | fn has_legacy_records(directory: &Path) -> Result<bool> { |
| 356 | for entry in fs::read_dir(directory)? { |
| 357 | if entry? |
| 358 | .path() |
| 359 | .extension() |
| 360 | .is_some_and(|extension| extension == "json") |
| 361 | { |
| 362 | return Ok(true); |
| 363 | } |
| 364 | } |
| 365 | Ok(false) |
| 366 | } |
| 367 | |
| 368 | fn decode(raw: &str) -> Result<AgentMailEnvelope> { |
| 369 | let mail: AgentMailEnvelope = serde_json::from_str(raw)?; |
| 370 | mail.validate().map_err(|error| anyhow!(error))?; |
| 371 | Ok(mail) |
| 372 | } |
| 373 | |
| 374 | #[cfg(test)] |
| 375 | mod tests { |
| 376 | use super::*; |
| 377 | use chrono::Utc; |
| 378 | use codewhale_protocol::agent_mail::{ |
| 379 | AGENT_MAIL_SCHEMA_VERSION, AgentMailDeliveryMode, AgentMailSender, AgentMailStatus, |
| 380 | }; |
| 381 | |
| 382 | #[cfg(unix)] |
| 383 | #[test] |
| 384 | fn refuses_a_database_linked_to_another_file() { |
| 385 | let directory = tempfile::tempdir().unwrap(); |
| 386 | let store = AgentMailStore::new(directory.path().to_owned()); |
| 387 | let outside = directory.path().join("keep"); |
| 388 | fs::write(&outside, b"owned file").unwrap(); |
| 389 | fs::hard_link(&outside, store.database_path()).unwrap(); |
| 390 | assert!(store.list(None).is_err()); |
| 391 | assert_eq!(fs::read(outside).unwrap(), b"owned file"); |
| 392 | } |
| 393 | |
| 394 | fn address(owner: &str, thread: &str) -> AgentMailAddress { |
| 395 | AgentMailAddress { |
| 396 | owner_id: owner.into(), |
| 397 | workspace_id: "project".into(), |
| 398 | thread_id: thread.into(), |
| 399 | thread_only: false, |
| 400 | task_id: Some(thread.into()), |
| 401 | session_id: None, |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | fn queued_envelope(owner: &str) -> AgentMailEnvelope { |
| 406 | AgentMailEnvelope { |
| 407 | schema_version: AGENT_MAIL_SCHEMA_VERSION, |
| 408 | message_id: AgentMailMessageId::new(), |
| 409 | source: address(owner, "first"), |
| 410 | destination: address(owner, "second"), |
| 411 | sender: AgentMailSender { |
| 412 | identity: "first".into(), |
| 413 | display_label: "First".into(), |
| 414 | }, |
| 415 | summary: "Results available".into(), |
| 416 | evidence: Vec::new(), |
| 417 | delivery_mode: AgentMailDeliveryMode::QueueOnly, |
| 418 | trigger_turn: false, |
| 419 | hop_count: 0, |
| 420 | status: AgentMailStatus::Queued, |
| 421 | created_at: Utc::now(), |
| 422 | delivered_at: None, |
| 423 | read_at: None, |
| 424 | attempt_count: 0, |
| 425 | failure: None, |
| 426 | delivery_turn_id: None, |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | #[test] |
| 431 | fn imported_envelope_is_durable_and_scoped_after_restart() { |
| 432 | let directory = tempfile::tempdir().unwrap(); |
| 433 | let mut envelope = queued_envelope("owner"); |
| 434 | let legacy = directory |
| 435 | .path() |
| 436 | .join(format!("{}.json", envelope.message_id)); |
| 437 | fs::write(&legacy, serde_json::to_vec(&envelope).unwrap()).unwrap(); |
| 438 | let store = AgentMailStore::new(directory.path().to_owned()); |
| 439 | assert!( |
| 440 | store |
| 441 | .mission_events("workspace-a:mission-1", "owner", 0, 10) |
| 442 | .unwrap() |
| 443 | .is_empty() |
| 444 | ); |
| 445 | assert!(!store.database_path().exists()); |
| 446 | let receipt = store.load(&envelope.message_id).unwrap().unwrap(); |
| 447 | assert_eq!(receipt, envelope); |
| 448 | envelope.status = AgentMailStatus::Canceled; |
| 449 | store.save(&envelope).unwrap(); |
| 450 | let reopened = AgentMailStore::new(directory.path().to_owned()); |
| 451 | assert_eq!( |
| 452 | reopened.list(Some(&address("owner", "second"))).unwrap(), |
| 453 | [envelope.clone()] |
| 454 | ); |
| 455 | let mut other = address("owner", "second"); |
| 456 | other.task_id = Some("later-execution".into()); |
| 457 | assert!(reopened.list(Some(&other)).unwrap().is_empty()); |
| 458 | assert_eq!( |
| 459 | decode(&fs::read_to_string(legacy).unwrap()).unwrap().status, |
| 460 | AgentMailStatus::Queued |
| 461 | ); |
| 462 | assert_eq!(reopened.list(None).unwrap(), [envelope.clone()]); |
| 463 | |
| 464 | let mut first = envelope.clone(); |
| 465 | first.message_id = AgentMailMessageId::new(); |
| 466 | first.status = AgentMailStatus::Queued; |
| 467 | let mut second = first.clone(); |
| 468 | second.message_id = AgentMailMessageId::new(); |
| 469 | reopened |
| 470 | .save_in_scope(&first, Some("workspace-a:mission-1")) |
| 471 | .unwrap(); |
| 472 | reopened |
| 473 | .save_in_scope(&second, Some("workspace-a:mission-2")) |
| 474 | .unwrap(); |
| 475 | first.status = AgentMailStatus::Canceled; |
| 476 | reopened.save(&first).unwrap(); |
| 477 | reopened.save(&first).unwrap(); |
| 478 | let restarted = AgentMailStore::new(directory.path().to_owned()); |
| 479 | let initial = restarted |
| 480 | .mission_events("workspace-a:mission-1", "owner", 0, 1) |
| 481 | .unwrap(); |
| 482 | assert_eq!(initial[0].envelope.status, AgentMailStatus::Queued); |
| 483 | let visible = restarted |
| 484 | .mission_events("workspace-a:mission-1", "owner", initial[0].sequence, 10) |
| 485 | .unwrap(); |
| 486 | assert_eq!(visible.len(), 1); |
| 487 | assert_eq!(visible[0].envelope, first); |
| 488 | assert_eq!( |
| 489 | restarted |
| 490 | .recent_mission_events("workspace-a:mission-1", "owner", 1) |
| 491 | .unwrap(), |
| 492 | visible |
| 493 | ); |
| 494 | assert_ne!( |
| 495 | restarted |
| 496 | .recent_mission_events("workspace-a:mission-2", "owner", 1) |
| 497 | .unwrap()[0] |
| 498 | .envelope |
| 499 | .message_id, |
| 500 | first.message_id |
| 501 | ); |
| 502 | assert!( |
| 503 | restarted |
| 504 | .mission_events("workspace-a:mission-1", "owner", u64::MAX, 10) |
| 505 | .unwrap() |
| 506 | .is_empty() |
| 507 | ); |
| 508 | let other_run = restarted |
| 509 | .mission_events("workspace-a:mission-2", "owner", 0, 10) |
| 510 | .unwrap(); |
| 511 | assert_eq!(other_run.len(), 1); |
| 512 | assert_eq!(other_run[0].envelope, second); |
| 513 | assert!( |
| 514 | restarted |
| 515 | .mission_events("workspace-b:mission-1", "owner", 0, 10) |
| 516 | .unwrap() |
| 517 | .is_empty() |
| 518 | ); |
| 519 | } |
| 520 | |
| 521 | #[test] |
| 522 | fn mission_replay_is_limited_to_both_addresses_of_the_current_owner() -> Result<()> { |
| 523 | use super::super::{AGENT_MAIL_OWNER_FILE, RuntimeThreadStore, manager}; |
| 524 | |
| 525 | let fixture = tempfile::tempdir()?; |
| 526 | let root = fixture.path().join("runtime"); |
| 527 | let workspace = fixture.path(); |
| 528 | let run = "mission-1"; |
| 529 | let scope = format!("{}:{run}", manager::agent_mail_workspace_id(workspace)?); |
| 530 | let old = RuntimeThreadStore::open(root.clone())?; |
| 531 | let stale = queued_envelope(&old.owner_id); |
| 532 | old.mail_store.save_in_scope(&stale, Some(&scope))?; |
| 533 | let reader = RuntimeThreadStore::open_read_only(root.clone())?.unwrap(); |
| 534 | assert_eq!( |
| 535 | reader.recent_mission_mail(workspace, run, 1)?[0].envelope, |
| 536 | stale |
| 537 | ); |
| 538 | drop(old); |
| 539 | |
| 540 | let owner_path = root.join(AGENT_MAIL_OWNER_FILE); |
| 541 | fs::remove_file(&owner_path)?; |
| 542 | assert!(reader.recent_mission_mail(workspace, run, 1)?.is_empty()); |
| 543 | assert!(!owner_path.exists()); |
| 544 | let current = RuntimeThreadStore::open(root)?; |
| 545 | assert_ne!(current.owner_id, stale.source.owner_id); |
| 546 | assert!(reader.recent_mission_mail(workspace, run, 1)?.is_empty()); |
| 547 | |
| 548 | let good = queued_envelope(¤t.owner_id); |
| 549 | current.mail_store.save_in_scope(&good, Some(&scope))?; |
| 550 | let mut foreign_sender = queued_envelope(¤t.owner_id); |
| 551 | foreign_sender |
| 552 | .source |
| 553 | .owner_id |
| 554 | .clone_from(&stale.source.owner_id); |
| 555 | current |
| 556 | .mail_store |
| 557 | .save_in_scope(&foreign_sender, Some(&scope))?; |
| 558 | let mut foreign_recipient = queued_envelope(¤t.owner_id); |
| 559 | foreign_recipient |
| 560 | .destination |
| 561 | .owner_id |
| 562 | .clone_from(&stale.destination.owner_id); |
| 563 | current |
| 564 | .mail_store |
| 565 | .save_in_scope(&foreign_recipient, Some(&scope))?; |
| 566 | let ascending = current |
| 567 | .mail_store |
| 568 | .mission_events(&scope, ¤t.owner_id, 0, 1)?; |
| 569 | let descending = reader.recent_mission_mail(workspace, run, 1)?; |
| 570 | assert_eq!(ascending.len(), 1); |
| 571 | assert_eq!(ascending[0].envelope, good); |
| 572 | assert_eq!(descending, ascending); |
| 573 | Ok(()) |
| 574 | } |
| 575 | } |
| 576 |