| 1 | use serde::de::DeserializeOwned; |
| 2 | use serde::de::value::UnitDeserializer; |
| 3 | use serde::{Deserialize, Deserializer, Serialize, Serializer}; |
| 4 | |
| 5 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] |
| 6 | #[serde(rename_all = "snake_case")] |
| 7 | pub enum FailureCode { |
| 8 | NotFound, |
| 9 | Forbidden, |
| 10 | Unauthenticated, |
| 11 | Conflict, |
| 12 | Invalid, |
| 13 | /// The workspace has to pay before this can happen. |
| 14 | PaymentRequired, |
| 15 | // Billing's refusals to start compute (`reserve`), each with a message |
| 16 | // that says what to do. See `g1t_contracts::billing::ReserveArgs`. |
| 17 | /// No plan, and no trial or pool that pays for this kind of work: a |
| 18 | /// card check or the g1t plan is needed. |
| 19 | NotPaid, |
| 20 | /// The workspace's one trial is spent. |
| 21 | TrialUsed, |
| 22 | /// The workspace reached its spend limit or g1t's ceiling. |
| 23 | Limit, |
| 24 | /// Compute is paused: a spend spike waiting for an owner, or a hold. |
| 25 | Paused, |
| 26 | /// This month's open-source pool, or the repository's share, is spent. |
| 27 | OssPoolEmpty, |
| 28 | /// A sensitive change needs the person to prove it is them again: a |
| 29 | /// recent sign-in, or their password. See `identity::Reauth`. |
| 30 | ReauthRequired, |
| 31 | /// Another host g1t depends on for this did not answer. |
| 32 | Unavailable, |
| 33 | /// What was sent is larger than this takes, such as an attachment over 10 MB. |
| 34 | TooLarge, |
| 35 | /// What was sent is not of a type this takes, such as an attachment that is not an image. |
| 36 | UnsupportedType, |
| 37 | } |
| 38 | |
| 39 | impl FailureCode { |
| 40 | pub fn http_status(self) -> u16 { |
| 41 | match self { |
| 42 | FailureCode::NotFound => 404, |
| 43 | FailureCode::Forbidden => 403, |
| 44 | FailureCode::Unauthenticated => 401, |
| 45 | FailureCode::Conflict => 409, |
| 46 | FailureCode::Invalid => 422, |
| 47 | FailureCode::PaymentRequired |
| 48 | | FailureCode::NotPaid |
| 49 | | FailureCode::TrialUsed |
| 50 | | FailureCode::Limit |
| 51 | | FailureCode::OssPoolEmpty => 402, |
| 52 | FailureCode::Paused => 409, |
| 53 | FailureCode::ReauthRequired => 403, |
| 54 | FailureCode::Unavailable => 503, |
| 55 | FailureCode::TooLarge => 413, |
| 56 | FailureCode::UnsupportedType => 415, |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | #[derive(Clone, Debug, Serialize, Deserialize)] |
| 62 | pub struct Failure { |
| 63 | pub code: FailureCode, |
| 64 | pub message: String, |
| 65 | } |
| 66 | |
| 67 | /// The result of a service call. Expected failures cross service boundaries |
| 68 | /// as values, so callers have to handle them. |
| 69 | /// |
| 70 | /// On the wire: `{"ok": true, "value": …}` or `{"ok": false, "error": …}`. |
| 71 | #[derive(Clone, Debug)] |
| 72 | pub enum Outcome<T> { |
| 73 | Ok(T), |
| 74 | Fail(Failure), |
| 75 | } |
| 76 | |
| 77 | impl<T> Outcome<T> { |
| 78 | pub fn fail(code: FailureCode, message: impl Into<String>) -> Self { |
| 79 | Outcome::Fail(Failure { |
| 80 | code, |
| 81 | message: message.into(), |
| 82 | }) |
| 83 | } |
| 84 | |
| 85 | pub fn into_result(self) -> Result<T, Failure> { |
| 86 | match self { |
| 87 | Outcome::Ok(value) => Ok(value), |
| 88 | Outcome::Fail(failure) => Err(failure), |
| 89 | } |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | #[derive(Serialize, Deserialize)] |
| 94 | #[serde(bound(serialize = "T: Serialize", deserialize = "T: DeserializeOwned"))] |
| 95 | struct Wire<T> { |
| 96 | ok: bool, |
| 97 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 98 | value: Option<T>, |
| 99 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 100 | error: Option<Failure>, |
| 101 | } |
| 102 | |
| 103 | impl<T: Serialize> Serialize for Outcome<T> { |
| 104 | fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { |
| 105 | match self { |
| 106 | Outcome::Ok(value) => Wire { |
| 107 | ok: true, |
| 108 | value: Some(value), |
| 109 | error: None, |
| 110 | }, |
| 111 | Outcome::Fail(failure) => Wire { |
| 112 | ok: false, |
| 113 | value: None, |
| 114 | error: Some(failure.clone()), |
| 115 | }, |
| 116 | } |
| 117 | .serialize(serializer) |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | impl<'de, T: DeserializeOwned> Deserialize<'de> for Outcome<T> { |
| 122 | fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { |
| 123 | let wire = Wire::<T>::deserialize(deserializer)?; |
| 124 | match (wire.ok, wire.value, wire.error) { |
| 125 | (true, Some(value), _) => Ok(Outcome::Ok(value)), |
| 126 | (false, _, Some(error)) => Ok(Outcome::Fail(error)), |
| 127 | // `"value": null`, or no value: what `Ok(None)` and `Ok(())` are |
| 128 | // written as. `Option<Option<T>>` reads a null as the outer |
| 129 | // `None`, so the value is read from nothing instead: `None` for |
| 130 | // an `Option`, `()` for a unit, and still malformed for a type |
| 131 | // that needs a value. |
| 132 | (true, None, _) => T::deserialize(UnitDeserializer::<D::Error>::new()) |
| 133 | .map(Outcome::Ok) |
| 134 | .map_err(|_| serde::de::Error::custom("malformed outcome: ok without a value")), |
| 135 | _ => Err(serde::de::Error::custom("malformed outcome")), |
| 136 | } |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | #[cfg(test)] |
| 141 | mod tests { |
| 142 | use super::*; |
| 143 | |
| 144 | fn round_trip<T: Serialize + DeserializeOwned>(outcome: &Outcome<T>) -> Result<Outcome<T>, String> { |
| 145 | // As a service replies (`g1t_kit::reply`) and its caller reads it |
| 146 | // (`g1t_kit::call`). |
| 147 | let wire = serde_json::to_string(outcome).map_err(|e| e.to_string())?; |
| 148 | serde_json::from_str(&wire).map_err(|e| e.to_string()) |
| 149 | } |
| 150 | |
| 151 | /// A cache miss is `Ok(None)`, written `{"ok":true,"value":null}`. It |
| 152 | /// was read back as malformed, so every miss of the toolkit's cache |
| 153 | /// (sccache's first lookup, `sccache/.sccache_check`) was a 500. |
| 154 | #[test] |
| 155 | fn ok_none_and_ok_unit_cross_the_wire() { |
| 156 | assert_eq!(serde_json::to_string(&Outcome::<Option<u8>>::Ok(None)).unwrap(), r#"{"ok":true,"value":null}"#); |
| 157 | assert!(matches!(round_trip(&Outcome::<Option<u8>>::Ok(None)), Ok(Outcome::Ok(None)))); |
| 158 | assert!(matches!(round_trip(&Outcome::Ok(Some(7u8))), Ok(Outcome::Ok(Some(7))))); |
| 159 | assert!(matches!(round_trip(&Outcome::Ok(())), Ok(Outcome::Ok(())))); |
| 160 | assert!(matches!(serde_json::from_str::<Outcome<Option<u8>>>(r#"{"ok":true}"#), Ok(Outcome::Ok(None)))); |
| 161 | let failed = round_trip(&Outcome::<Option<u8>>::fail(FailureCode::Unauthenticated, "no")); |
| 162 | assert!(matches!(failed, Ok(Outcome::Fail(Failure { code: FailureCode::Unauthenticated, .. })))); |
| 163 | } |
| 164 | |
| 165 | #[test] |
| 166 | fn an_ok_without_the_value_it_needs_is_still_malformed() { |
| 167 | assert!(serde_json::from_str::<Outcome<u8>>(r#"{"ok":true,"value":null}"#).is_err()); |
| 168 | assert!(serde_json::from_str::<Outcome<String>>(r#"{"ok":true}"#).is_err()); |
| 169 | assert!(serde_json::from_str::<Outcome<u8>>(r#"{"ok":false}"#).is_err()); |
| 170 | } |
| 171 | } |