| 1 | use super::*; |
| 2 | use codewhale_engine::whale_soul::{self, Soul}; |
| 3 | |
| 4 | pub(super) async fn get() -> Result<Json<Soul>, ApiError> { |
| 5 | codewhale_runtime::runtime_control::owner_work(whale_soul::load) |
| 6 | .await |
| 7 | .map(Json) |
| 8 | .map_err(|error| ApiError::conflict(error.to_string())) |
| 9 | } |
| 10 | |
| 11 | #[derive(Deserialize)] |
| 12 | #[serde(deny_unknown_fields)] |
| 13 | pub(super) struct Edit { |
| 14 | text: String, |
| 15 | } |
| 16 | |
| 17 | pub(super) async fn save( |
| 18 | headers: HeaderMap, |
| 19 | Json(edit): Json<Edit>, |
| 20 | ) -> Result<Json<Soul>, ApiError> { |
| 21 | let expected = headers |
| 22 | .get("if-match") |
| 23 | .and_then(|value| value.to_str().ok()) |
| 24 | .and_then(|value| value.strip_prefix('"')?.strip_suffix('"')) |
| 25 | .filter(|value| { |
| 26 | *value == "new" |
| 27 | || (value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit())) |
| 28 | }) |
| 29 | .ok_or_else(|| ApiError::bad_request("Read SOUL.md and send its revision in If-Match"))? |
| 30 | .to_owned(); |
| 31 | if edit.text.len() > whale_soul::MAX_BYTES { |
| 32 | return Err(ApiError::bad_request( |
| 33 | "SOUL.md exceeds the local whale file limit", |
| 34 | )); |
| 35 | } |
| 36 | codewhale_runtime::runtime_control::owner_work(move || whale_soul::save(&expected, &edit.text)) |
| 37 | .await |
| 38 | .map_err(|error| ApiError::conflict(error.to_string()))? |
| 39 | .map(Json) |
| 40 | .ok_or_else(|| ApiError { |
| 41 | status: StatusCode::PRECONDITION_FAILED, |
| 42 | code: None, |
| 43 | message: "SOUL.md changed since it was opened".into(), |
| 44 | }) |
| 45 | } |
| 46 |