| 1 | use super::*; |
| 2 | use ring::hmac; |
| 3 | use std::sync::{Mutex as StdMutex, TryLockError}; |
| 4 | |
| 5 | static JOB_OPERATION_MUTEX: StdMutex<()> = StdMutex::new(()); |
| 6 | |
| 7 | #[derive(Debug, thiserror::Error)] |
| 8 | #[error("job operation admission is busy")] |
| 9 | pub struct JobOperationsBusy; |
| 10 | |
| 11 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 12 | #[serde(deny_unknown_fields)] |
| 13 | pub struct JobOperation { |
| 14 | pub id: String, |
| 15 | pub store_id: String, |
| 16 | pub thread_id: String, |
| 17 | pub workspace: PathBuf, |
| 18 | pub cwd: PathBuf, |
| 19 | pub purpose: String, |
| 20 | pub status: String, |
| 21 | pub job_id: Option<String>, |
| 22 | pub job_status: Option<String>, |
| 23 | pub exit_code: Option<i64>, |
| 24 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 25 | pub stop_reason: Option<crate::tools::shell::ShellJobStopReason>, |
| 26 | pub created_at_ms: i64, |
| 27 | pub updated_at_ms: i64, |
| 28 | } |
| 29 | |
| 30 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 31 | #[serde(deny_unknown_fields)] |
| 32 | pub struct JobOperationRecord { |
| 33 | pub schema_version: u32, |
| 34 | pub operation: JobOperation, |
| 35 | pub request_fingerprint: String, |
| 36 | pub owner_generation: String, |
| 37 | } |
| 38 | |
| 39 | pub struct JobOperationTransaction<'a> { |
| 40 | store: &'a RuntimeThreadStore, |
| 41 | } |
| 42 | |
| 43 | pub fn validate_key(key: &str) -> Result<()> { |
| 44 | let id = Uuid::parse_str(key).context("invalid job operation key")?; |
| 45 | anyhow::ensure!( |
| 46 | id.get_version_num() == 4 && id.to_string() == key, |
| 47 | "invalid job operation key" |
| 48 | ); |
| 49 | Ok(()) |
| 50 | } |
| 51 | |
| 52 | pub fn request_fingerprint(key: &str, request: &[u8]) -> Result<String> { |
| 53 | validate_key(key)?; |
| 54 | let key = hmac::Key::new(hmac::HMAC_SHA256, key.as_bytes()); |
| 55 | Ok(hex_digest(hmac::sign(&key, request).as_ref())) |
| 56 | } |
| 57 | |
| 58 | impl RuntimeThreadStore { |
| 59 | pub fn with_job_operations<T>( |
| 60 | &self, |
| 61 | action: impl FnOnce(&JobOperationTransaction<'_>) -> Result<T>, |
| 62 | ) -> Result<T> { |
| 63 | let _local = match JOB_OPERATION_MUTEX.try_lock() { |
| 64 | Ok(guard) => guard, |
| 65 | Err(TryLockError::WouldBlock) => return Err(JobOperationsBusy.into()), |
| 66 | Err(TryLockError::Poisoned(_)) => bail!("job operation admission unavailable"), |
| 67 | }; |
| 68 | let root = self |
| 69 | .job_operations_dir |
| 70 | .parent() |
| 71 | .context("missing runtime store root")?; |
| 72 | checked_existing_runtime_store_dir(&self.job_operations_dir)?; |
| 73 | let path = root.join("job-operations.lock"); |
| 74 | let file = open_runtime_store_file(&path, "job operation lock", |options| { |
| 75 | options.create(true).truncate(false).read(true).write(true); |
| 76 | })?; |
| 77 | let mut lock = fd_lock::RwLock::new(file); |
| 78 | let guard = match lock.try_write() { |
| 79 | Ok(guard) => guard, |
| 80 | Err(error) |
| 81 | if matches!( |
| 82 | error.kind(), |
| 83 | io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted |
| 84 | ) => |
| 85 | { |
| 86 | return Err(JobOperationsBusy.into()); |
| 87 | } |
| 88 | Err(error) => return Err(error).context("job operation lock unavailable"), |
| 89 | }; |
| 90 | anyhow::ensure!( |
| 91 | owner_lock_is_at_path(&guard, &path)?, |
| 92 | "job operation lock changed" |
| 93 | ); |
| 94 | action(&JobOperationTransaction { store: self }) |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | impl JobOperationTransaction<'_> { |
| 99 | pub fn operation_id(&self, thread_id: &str, key: &str) -> Result<String> { |
| 100 | validated_record_id(thread_id, "job operation thread")?; |
| 101 | validate_key(key)?; |
| 102 | Ok(codewhale_runtime::hashing::sha256_hex(format!( |
| 103 | "runtime-job-operation\u{1f}{}\u{1f}{thread_id}\u{1f}{key}", |
| 104 | self.store.owner_id |
| 105 | ))) |
| 106 | } |
| 107 | |
| 108 | fn path(&self, id: &str) -> Result<PathBuf> { |
| 109 | validate_sha256_fingerprint(id, "job operation id")?; |
| 110 | RuntimeThreadStore::record_path( |
| 111 | &self.store.job_operations_dir, |
| 112 | id, |
| 113 | "json", |
| 114 | "job operation id", |
| 115 | ) |
| 116 | } |
| 117 | |
| 118 | fn validate(&self, record: &JobOperationRecord) -> Result<()> { |
| 119 | let operation = &record.operation; |
| 120 | anyhow::ensure!( |
| 121 | record.schema_version == 1, |
| 122 | "unsupported job operation schema" |
| 123 | ); |
| 124 | validate_sha256_fingerprint(&operation.id, "job operation id")?; |
| 125 | validate_sha256_fingerprint(&record.request_fingerprint, "job request fingerprint")?; |
| 126 | validated_record_id(&operation.thread_id, "job operation thread")?; |
| 127 | anyhow::ensure!( |
| 128 | operation.store_id == self.store.owner_id, |
| 129 | "job operation store mismatch" |
| 130 | ); |
| 131 | anyhow::ensure!( |
| 132 | operation.workspace.is_absolute() && operation.cwd.is_absolute(), |
| 133 | "invalid job operation workspace" |
| 134 | ); |
| 135 | anyhow::ensure!( |
| 136 | matches!( |
| 137 | operation.purpose.as_str(), |
| 138 | "setup" | "run" | "archive" | "command" |
| 139 | ), |
| 140 | "invalid job purpose" |
| 141 | ); |
| 142 | anyhow::ensure!( |
| 143 | matches!( |
| 144 | operation.status.as_str(), |
| 145 | "running" | "completed" | "rejected" | "unknown" |
| 146 | ), |
| 147 | "invalid job status" |
| 148 | ); |
| 149 | if let Some(id) = &operation.job_id { |
| 150 | validated_record_id(id, "job id")?; |
| 151 | anyhow::ensure!( |
| 152 | id.starts_with("shell_") && id.len() <= 128, |
| 153 | "invalid job id" |
| 154 | ); |
| 155 | } |
| 156 | anyhow::ensure!( |
| 157 | operation.created_at_ms > 0 && operation.updated_at_ms >= operation.created_at_ms, |
| 158 | "invalid job operation timestamps" |
| 159 | ); |
| 160 | anyhow::ensure!( |
| 161 | operation.status == "completed" |
| 162 | || (operation.job_status.is_none() && operation.exit_code.is_none()), |
| 163 | "nonterminal job operation has a terminal result" |
| 164 | ); |
| 165 | anyhow::ensure!( |
| 166 | operation.status != "rejected" || operation.job_id.is_none(), |
| 167 | "rejected job operation has a job id" |
| 168 | ); |
| 169 | anyhow::ensure!( |
| 170 | operation.status != "running" || operation.job_id.is_some(), |
| 171 | "running job operation has no job id" |
| 172 | ); |
| 173 | anyhow::ensure!( |
| 174 | operation.status != "completed" |
| 175 | || (operation.job_id.is_some() |
| 176 | && operation |
| 177 | .job_status |
| 178 | .as_deref() |
| 179 | .is_some_and(|status| matches!( |
| 180 | status, |
| 181 | "Completed" | "Failed" | "Killed" | "TimedOut" |
| 182 | ))), |
| 183 | "completed job operation has no terminal result" |
| 184 | ); |
| 185 | anyhow::ensure!( |
| 186 | Uuid::parse_str(&record.owner_generation).is_ok_and(|id| id.get_version_num() == 4), |
| 187 | "invalid job owner generation" |
| 188 | ); |
| 189 | Ok(()) |
| 190 | } |
| 191 | |
| 192 | pub fn get(&self, id: &str) -> Result<Option<JobOperationRecord>> { |
| 193 | let path = self.path(id)?; |
| 194 | let raw = match read_store_file(&path) { |
| 195 | Ok(raw) => raw, |
| 196 | Err(error) |
| 197 | if error |
| 198 | .downcast_ref::<io::Error>() |
| 199 | .is_some_and(|error| error.kind() == io::ErrorKind::NotFound) => |
| 200 | { |
| 201 | return Ok(None); |
| 202 | } |
| 203 | Err(error) => return Err(error), |
| 204 | }; |
| 205 | let record: JobOperationRecord = serde_json::from_str(&raw)?; |
| 206 | self.validate(&record)?; |
| 207 | anyhow::ensure!(record.operation.id == id, "job operation path mismatch"); |
| 208 | Ok(Some(record)) |
| 209 | } |
| 210 | |
| 211 | pub fn list(&self) -> Result<Vec<JobOperationRecord>> { |
| 212 | let directory = checked_existing_runtime_store_dir(&self.store.job_operations_dir)?; |
| 213 | let mut records = Vec::new(); |
| 214 | for entry in fs::read_dir(directory)? { |
| 215 | let path = entry?.path(); |
| 216 | if path.extension().is_none_or(|ext| ext != "json") { |
| 217 | continue; |
| 218 | } |
| 219 | let id = path |
| 220 | .file_stem() |
| 221 | .and_then(|name| name.to_str()) |
| 222 | .context("invalid job operation filename")?; |
| 223 | records.push(self.get(id)?.context("job operation disappeared")?); |
| 224 | } |
| 225 | records.sort_by(|a, b| { |
| 226 | a.operation |
| 227 | .created_at_ms |
| 228 | .cmp(&b.operation.created_at_ms) |
| 229 | .then_with(|| a.operation.id.cmp(&b.operation.id)) |
| 230 | }); |
| 231 | Ok(records) |
| 232 | } |
| 233 | |
| 234 | pub fn save(&self, record: &JobOperationRecord) -> Result<()> { |
| 235 | self.validate(record)?; |
| 236 | write_json_atomic(&self.path(&record.operation.id)?, record) |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | pub const MEMBER_RESERVED: &str = "reserved"; |
| 241 | pub const MEMBER_ACCEPTED: &str = "accepted"; |
| 242 | pub const MEMBER_ABANDONED: &str = "abandoned"; |
| 243 | pub const MEMBER_UNKNOWN: &str = "unknown"; |
| 244 | |
| 245 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 246 | #[serde(deny_unknown_fields)] |
| 247 | pub struct MemberOperation { |
| 248 | pub id: String, |
| 249 | pub store_id: String, |
| 250 | pub thread_id: String, |
| 251 | pub member_id: String, |
| 252 | pub operation_key: String, |
| 253 | pub agent_id: String, |
| 254 | pub state: String, |
| 255 | pub created_at_ms: i64, |
| 256 | pub updated_at_ms: i64, |
| 257 | } |
| 258 | |
| 259 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 260 | #[serde(deny_unknown_fields)] |
| 261 | pub struct MemberOperationRecord { |
| 262 | pub schema_version: u32, |
| 263 | pub operation: MemberOperation, |
| 264 | pub request_fingerprint: String, |
| 265 | pub owner_generation: String, |
| 266 | } |
| 267 | |
| 268 | pub fn valid_member_key(value: &str) -> bool { |
| 269 | !value.is_empty() |
| 270 | && value.len() <= 128 |
| 271 | && value.as_bytes()[0].is_ascii_alphanumeric() |
| 272 | && value |
| 273 | .bytes() |
| 274 | .all(|byte| byte.is_ascii_alphanumeric() || b"._:-".contains(&byte)) |
| 275 | } |
| 276 | |
| 277 | pub fn member_request_fingerprint( |
| 278 | thread_id: &str, |
| 279 | member_id: &str, |
| 280 | display_name: &str, |
| 281 | prompt: &str, |
| 282 | fleet: &impl Serialize, |
| 283 | ) -> Result<String> { |
| 284 | Ok(codewhale_runtime::hashing::sha256_hex(serde_json::to_vec( |
| 285 | &( |
| 286 | "runtime-member-request-v1", |
| 287 | thread_id, |
| 288 | member_id, |
| 289 | display_name, |
| 290 | prompt, |
| 291 | fleet, |
| 292 | ), |
| 293 | )?)) |
| 294 | } |
| 295 | |
| 296 | pub fn new_member_agent_id() -> String { |
| 297 | format!("agent_{}", &Uuid::new_v4().simple().to_string()[..12]) |
| 298 | } |
| 299 | |
| 300 | impl JobOperationTransaction<'_> { |
| 301 | fn member_dir(&self) -> Result<PathBuf> { |
| 302 | let dir = self |
| 303 | .store |
| 304 | .job_operations_dir |
| 305 | .parent() |
| 306 | .context("missing runtime store root")? |
| 307 | .join("member-operations"); |
| 308 | ensure_runtime_store_dir(&dir)?; |
| 309 | checked_existing_runtime_store_dir(&dir) |
| 310 | } |
| 311 | |
| 312 | pub fn member_operation_id(&self, thread_id: &str, key: &str) -> Result<String> { |
| 313 | validated_record_id(thread_id, "member operation thread")?; |
| 314 | anyhow::ensure!(valid_member_key(key), "invalid member operation key"); |
| 315 | Ok(codewhale_runtime::hashing::sha256_hex(format!( |
| 316 | "runtime-member-operation\u{1f}{}\u{1f}{thread_id}\u{1f}{key}", |
| 317 | self.store.owner_id |
| 318 | ))) |
| 319 | } |
| 320 | |
| 321 | fn member_path(&self, id: &str) -> Result<PathBuf> { |
| 322 | validate_sha256_fingerprint(id, "member operation id")?; |
| 323 | RuntimeThreadStore::record_path(&self.member_dir()?, id, "json", "member operation id") |
| 324 | } |
| 325 | |
| 326 | fn validate_member(&self, record: &MemberOperationRecord) -> Result<()> { |
| 327 | let operation = &record.operation; |
| 328 | anyhow::ensure!( |
| 329 | record.schema_version == 1, |
| 330 | "unsupported member operation schema" |
| 331 | ); |
| 332 | validate_sha256_fingerprint(&operation.id, "member operation id")?; |
| 333 | validate_sha256_fingerprint(&record.request_fingerprint, "member request fingerprint")?; |
| 334 | anyhow::ensure!( |
| 335 | operation.id |
| 336 | == self.member_operation_id(&operation.thread_id, &operation.operation_key)?, |
| 337 | "member operation identity mismatch" |
| 338 | ); |
| 339 | anyhow::ensure!( |
| 340 | operation.store_id == self.store.owner_id, |
| 341 | "member operation store mismatch" |
| 342 | ); |
| 343 | anyhow::ensure!( |
| 344 | valid_member_key(&operation.member_id), |
| 345 | "invalid member operation member" |
| 346 | ); |
| 347 | anyhow::ensure!( |
| 348 | operation.agent_id.starts_with("agent_") |
| 349 | && validated_record_id(&operation.agent_id, "member agent id").is_ok() |
| 350 | && operation.agent_id.len() <= 64, |
| 351 | "invalid member agent id" |
| 352 | ); |
| 353 | anyhow::ensure!( |
| 354 | matches!( |
| 355 | operation.state.as_str(), |
| 356 | MEMBER_RESERVED | MEMBER_ACCEPTED | MEMBER_ABANDONED |
| 357 | ), |
| 358 | "invalid member operation state" |
| 359 | ); |
| 360 | anyhow::ensure!( |
| 361 | operation.created_at_ms > 0 && operation.updated_at_ms >= operation.created_at_ms, |
| 362 | "invalid member operation timestamps" |
| 363 | ); |
| 364 | anyhow::ensure!( |
| 365 | Uuid::parse_str(&record.owner_generation).is_ok_and(|id| id.get_version_num() == 4), |
| 366 | "invalid member owner generation" |
| 367 | ); |
| 368 | Ok(()) |
| 369 | } |
| 370 | |
| 371 | pub fn get_member(&self, id: &str) -> Result<Option<MemberOperationRecord>> { |
| 372 | let path = self.member_path(id)?; |
| 373 | let raw = match read_store_file(&path) { |
| 374 | Ok(raw) => raw, |
| 375 | Err(error) |
| 376 | if error |
| 377 | .downcast_ref::<io::Error>() |
| 378 | .is_some_and(|error| error.kind() == io::ErrorKind::NotFound) => |
| 379 | { |
| 380 | return Ok(None); |
| 381 | } |
| 382 | Err(error) => return Err(error), |
| 383 | }; |
| 384 | let record: MemberOperationRecord = serde_json::from_str(&raw)?; |
| 385 | self.validate_member(&record)?; |
| 386 | anyhow::ensure!(record.operation.id == id, "member operation path mismatch"); |
| 387 | Ok(Some(record)) |
| 388 | } |
| 389 | |
| 390 | pub fn list_members(&self) -> Result<Vec<MemberOperationRecord>> { |
| 391 | let directory = self.member_dir()?; |
| 392 | let mut records = Vec::new(); |
| 393 | for entry in fs::read_dir(directory)? { |
| 394 | let path = entry?.path(); |
| 395 | if path.extension().is_none_or(|ext| ext != "json") { |
| 396 | continue; |
| 397 | } |
| 398 | let id = path |
| 399 | .file_stem() |
| 400 | .and_then(|name| name.to_str()) |
| 401 | .context("invalid member operation filename")?; |
| 402 | records.push( |
| 403 | self.get_member(id)? |
| 404 | .context("member operation disappeared")?, |
| 405 | ); |
| 406 | } |
| 407 | records.sort_by(|a, b| { |
| 408 | a.operation |
| 409 | .created_at_ms |
| 410 | .cmp(&b.operation.created_at_ms) |
| 411 | .then_with(|| a.operation.id.cmp(&b.operation.id)) |
| 412 | }); |
| 413 | Ok(records) |
| 414 | } |
| 415 | |
| 416 | pub fn save_member(&self, record: &MemberOperationRecord) -> Result<()> { |
| 417 | self.validate_member(record)?; |
| 418 | write_json_atomic(&self.member_path(&record.operation.id)?, record) |
| 419 | } |
| 420 | |
| 421 | pub fn remove_member(&self, id: &str) -> Result<()> { |
| 422 | remove_file_if_exists(&self.member_path(id)?) |
| 423 | } |
| 424 | |
| 425 | pub fn thread_has_pending_member_operation( |
| 426 | &self, |
| 427 | thread_id: &str, |
| 428 | generation: Option<&str>, |
| 429 | ) -> Result<bool> { |
| 430 | Ok(self.list_members()?.iter().any(|record| { |
| 431 | record.operation.thread_id == thread_id |
| 432 | && record.operation.state == MEMBER_RESERVED |
| 433 | && generation.is_none_or(|generation| record.owner_generation == generation) |
| 434 | })) |
| 435 | } |
| 436 | |
| 437 | pub fn remove_thread_members(&self, thread_id: &str) -> Result<()> { |
| 438 | for record in self.list_members()? { |
| 439 | if record.operation.thread_id == thread_id { |
| 440 | self.remove_member(&record.operation.id)?; |
| 441 | } |
| 442 | } |
| 443 | Ok(()) |
| 444 | } |
| 445 | } |
| 446 |