| 1 | //! Decision records: why the work is the way it is, and how sure that is. |
| 2 | //! |
| 3 | //! g1t keeps the ones it saw proved itself: what the merge queue found when |
| 4 | //! it combined pull requests (`tested`), a person's approval (`approved`) |
| 5 | //! and merges. `record_decision` keeps an agent's or a person's own |
| 6 | //! reasons, as `claimed`. Each is published as `decision.recorded`. |
| 7 | |
| 8 | use g1t_contracts::access::Capability; |
| 9 | use g1t_contracts::decisions::{ |
| 10 | Decision, DecisionConfidence, DecisionKind, DecisionRecorded, ListDecisionsArgs, RecordDecisionArgs, |
| 11 | }; |
| 12 | use g1t_contracts::time::rfc3339; |
| 13 | use g1t_contracts::{FailureCode, Outcome, User, new_id}; |
| 14 | use g1t_kit::now_ms; |
| 15 | use serde::Deserialize; |
| 16 | use serde_json::{Value, json}; |
| 17 | use worker::Result; |
| 18 | use worker::wasm_bindgen::JsValue; |
| 19 | |
| 20 | use crate::Work; |
| 21 | |
| 22 | /// The longest summary kept. |
| 23 | pub(crate) const MAX_SUMMARY_CHARS: usize = 2000; |
| 24 | /// The most evidence kept, as JSON. |
| 25 | pub(crate) const MAX_EVIDENCE_BYTES: usize = 8 * 1024; |
| 26 | /// The most decisions one list returns. |
| 27 | const LIST_LIMIT: u32 = 200; |
| 28 | |
| 29 | /// A decision about to be kept. |
| 30 | pub(crate) struct NewDecision<'a> { |
| 31 | /// The work item it is about, by id. |
| 32 | pub(crate) item: Option<String>, |
| 33 | pub(crate) pull: Option<u32>, |
| 34 | pub(crate) session_id: Option<String>, |
| 35 | /// Who recorded it; `None` for g1t itself. |
| 36 | pub(crate) actor: Option<&'a User>, |
| 37 | pub(crate) kind: DecisionKind, |
| 38 | pub(crate) confidence: DecisionConfidence, |
| 39 | pub(crate) summary: String, |
| 40 | pub(crate) evidence: Value, |
| 41 | } |
| 42 | |
| 43 | /// A decision's columns, with its work item's number. |
| 44 | const DECISION_COLUMNS: &str = "decisions.*, (SELECT number FROM work_items WHERE work_items.id = decisions.item_id) AS item"; |
| 45 | |
| 46 | #[derive(Deserialize)] |
| 47 | struct DecisionRow { |
| 48 | id: String, |
| 49 | #[serde(default)] |
| 50 | repo_id: String, |
| 51 | #[serde(default)] |
| 52 | item: Option<u32>, |
| 53 | pull: Option<u32>, |
| 54 | session_id: Option<String>, |
| 55 | actor_name: Option<String>, |
| 56 | kind: String, |
| 57 | confidence: String, |
| 58 | summary: String, |
| 59 | evidence: String, |
| 60 | created_at: String, |
| 61 | } |
| 62 | |
| 63 | impl DecisionRow { |
| 64 | fn decision(self) -> Option<Decision> { |
| 65 | Some(Decision { |
| 66 | kind: DecisionKind::parse(&self.kind)?, |
| 67 | confidence: serde_json::from_value(Value::String(self.confidence)).ok()?, |
| 68 | evidence: serde_json::from_str(&self.evidence).unwrap_or_else(|_| json!({})), |
| 69 | id: self.id, |
| 70 | item: self.item, |
| 71 | pull: self.pull, |
| 72 | session_id: self.session_id, |
| 73 | actor: self.actor_name, |
| 74 | summary: self.summary, |
| 75 | created_at: self.created_at, |
| 76 | }) |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | /// What `record_decision` keeps of what it was given: the summary, trimmed, |
| 81 | /// and the evidence as an object. Says what is wrong otherwise. |
| 82 | pub(crate) fn checked( |
| 83 | kind: DecisionKind, |
| 84 | summary: &str, |
| 85 | evidence: Option<&Value>, |
| 86 | session_id: Option<&str>, |
| 87 | ) -> std::result::Result<(String, Value), &'static str> { |
| 88 | if !DecisionKind::RECORDABLE.contains(&kind) { |
| 89 | return Err( |
| 90 | "kind must be proposal, claim, fix or note. g1t records integration results, approvals and merges itself.", |
| 91 | ); |
| 92 | } |
| 93 | let summary = summary.trim(); |
| 94 | if summary.is_empty() { |
| 95 | return Err("Give a summary: the decision, in a sentence or two."); |
| 96 | } |
| 97 | if summary.chars().count() > MAX_SUMMARY_CHARS { |
| 98 | return Err("The summary is too long: 2,000 characters at most."); |
| 99 | } |
| 100 | let evidence = match evidence { |
| 101 | None | Some(Value::Null) => json!({}), |
| 102 | Some(object @ Value::Object(_)) => object.clone(), |
| 103 | Some(_) => return Err("evidence must be an object, such as {\"commit\": \"…\"}."), |
| 104 | }; |
| 105 | if evidence.to_string().len() > MAX_EVIDENCE_BYTES { |
| 106 | return Err("The evidence is too large: 8 KB of JSON at most."); |
| 107 | } |
| 108 | if session_id.is_some_and(|id| id.len() > 100) { |
| 109 | return Err("session_id is not a session's id."); |
| 110 | } |
| 111 | Ok((summary.to_owned(), evidence)) |
| 112 | } |
| 113 | |
| 114 | /// Whether g1t itself acted: as itself, or by a repository's settings |
| 115 | /// (an older id it kept for those). |
| 116 | pub(crate) fn is_g1t(actor: &User) -> bool { |
| 117 | actor.is_system() || g1t_contracts::system::is_system_id(&actor.id) |
| 118 | } |
| 119 | |
| 120 | /// How sure a merge is: tested when the queue or the repository's own |
| 121 | /// rules landed it once its checks passed, approved when a person merged |
| 122 | /// it, claimed when an agent's token did. |
| 123 | pub(crate) fn merge_confidence(through_queue: bool, actor: &User) -> DecisionConfidence { |
| 124 | if through_queue || is_g1t(actor) { |
| 125 | DecisionConfidence::Tested |
| 126 | } else if g1t_contracts::rules::is_agent(actor) { |
| 127 | DecisionConfidence::Claimed |
| 128 | } else { |
| 129 | DecisionConfidence::Approved |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | /// How sure an approval is: a person's is approved, an agent's only |
| 134 | /// claimed. |
| 135 | pub(crate) fn approval_confidence(actor: &User) -> DecisionConfidence { |
| 136 | if g1t_contracts::rules::is_agent(actor) { |
| 137 | DecisionConfidence::Claimed |
| 138 | } else { |
| 139 | DecisionConfidence::Approved |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | impl Work { |
| 144 | /// Keeps a decision and publishes `decision.recorded`. |
| 145 | pub(crate) async fn keep_decision(&self, repo_id: &str, new: NewDecision<'_>) -> Result<Decision> { |
| 146 | let now = now_ms(); |
| 147 | let item = match &new.item { |
| 148 | Some(id) => self |
| 149 | .db |
| 150 | .prepare("SELECT number AS n FROM work_items WHERE id = ? AND number IS NOT NULL") |
| 151 | .bind(&[id.as_str().into()])? |
| 152 | .first::<crate::rows::NumberRow>(None) |
| 153 | .await? |
| 154 | .map(|row| row.n), |
| 155 | None => None, |
| 156 | }; |
| 157 | let decision = Decision { |
| 158 | id: new_id("dec", now), |
| 159 | item, |
| 160 | pull: new.pull, |
| 161 | session_id: new.session_id, |
| 162 | actor: new.actor.map(|actor| actor.username.clone()), |
| 163 | kind: new.kind, |
| 164 | confidence: new.confidence, |
| 165 | summary: new.summary, |
| 166 | evidence: new.evidence, |
| 167 | created_at: rfc3339(now), |
| 168 | }; |
| 169 | let number = |value: Option<u32>| value.map_or(JsValue::NULL, JsValue::from); |
| 170 | let event = serde_json::to_value(DecisionRecorded { |
| 171 | repo_id: repo_id.to_owned(), |
| 172 | number: decision.pull.or(decision.item).unwrap_or_default(), |
| 173 | item: decision.item, |
| 174 | decision: decision.clone(), |
| 175 | })?; |
| 176 | let mut statements = vec![self |
| 177 | .db |
| 178 | .prepare( |
| 179 | "INSERT INTO decisions |
| 180 | (id, repo_id, item_id, pull, session_id, actor, actor_name, kind, confidence, |
| 181 | summary, evidence, created_at) |
| 182 | VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", |
| 183 | ) |
| 184 | .bind(&[ |
| 185 | decision.id.as_str().into(), |
| 186 | repo_id.into(), |
| 187 | crate::optional(&new.item), |
| 188 | number(decision.pull), |
| 189 | decision.session_id.as_deref().map_or(JsValue::NULL, JsValue::from), |
| 190 | new.actor.map_or(JsValue::NULL, |actor| actor.id.as_str().into()), |
| 191 | decision.actor.as_deref().map_or(JsValue::NULL, JsValue::from), |
| 192 | decision.kind.as_str().into(), |
| 193 | decision.confidence.as_str().into(), |
| 194 | decision.summary.as_str().into(), |
| 195 | decision.evidence.to_string().into(), |
| 196 | decision.created_at.as_str().into(), |
| 197 | ])?]; |
| 198 | // Kept and delivered to the sessions it concerns in one change. |
| 199 | let sent = crate::coordination::updates::push_delivery( |
| 200 | &mut statements, |
| 201 | self.delivery("decision.recorded", repo_id, event.clone(), &decision.id, "1", Vec::new())?, |
| 202 | ); |
| 203 | self.db.batch(statements).await?; |
| 204 | self.delivered(sent, "decision.recorded", repo_id, new.actor.map(|actor| actor.id.clone()), event).await?; |
| 205 | Ok(decision) |
| 206 | } |
| 207 | |
| 208 | /// Keeps a decision without failing what it records: a decision that |
| 209 | /// could not be kept only logs. |
| 210 | pub(crate) async fn keep_decision_quietly(&self, repo_id: &str, new: NewDecision<'_>) { |
| 211 | if let Err(error) = self.keep_decision(repo_id, new).await { |
| 212 | worker::console_warn!("decision not kept: {error}"); |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | /// `record_decision`: an agent's or a person's reason on a pull |
| 217 | /// request, kept as claimed. |
| 218 | pub(crate) async fn record_decision(&self, a: RecordDecisionArgs) -> Result<Outcome<Decision>> { |
| 219 | let (summary, evidence) = |
| 220 | match checked(a.kind, &a.summary, a.evidence.as_ref(), a.session_id.as_deref()) { |
| 221 | Ok(checked) => checked, |
| 222 | Err(message) => return Ok(Outcome::fail(FailureCode::Invalid, message)), |
| 223 | }; |
| 224 | let viewer = Some(a.actor.clone()); |
| 225 | let (repo, pull) = match self.pull_at(&a.repo, a.number, &viewer).await? { |
| 226 | Outcome::Ok(found) => found, |
| 227 | Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)), |
| 228 | }; |
| 229 | if let Outcome::Fail(failure) = crate::retired::writable(&repo) { |
| 230 | return Ok(Outcome::Fail(failure)); |
| 231 | } |
| 232 | if !a.actor.verified { |
| 233 | return Ok(Outcome::fail(FailureCode::Forbidden, crate::UNVERIFIED)); |
| 234 | } |
| 235 | if !pull.is_owned_by(&a.actor.id) |
| 236 | && let Outcome::Fail(failure) = crate::allowed(Some(&a.actor), &repo, Capability::Participate) |
| 237 | { |
| 238 | return Ok(Outcome::Fail(failure)); |
| 239 | } |
| 240 | let decision = self |
| 241 | .keep_decision( |
| 242 | &repo.id, |
| 243 | NewDecision { |
| 244 | item: self.pull_item_id(&pull.id).await?, |
| 245 | pull: Some(pull.number), |
| 246 | session_id: a.session_id, |
| 247 | actor: Some(&a.actor), |
| 248 | kind: a.kind, |
| 249 | confidence: DecisionConfidence::Claimed, |
| 250 | summary, |
| 251 | evidence, |
| 252 | }, |
| 253 | ) |
| 254 | .await?; |
| 255 | Ok(Outcome::Ok(decision)) |
| 256 | } |
| 257 | |
| 258 | /// `list_decisions`: a work item's, with those on its pull requests in |
| 259 | /// the repositories the viewer may read, or a pull request's, oldest |
| 260 | /// first. |
| 261 | pub(crate) async fn list_decisions(&self, a: ListDecisionsArgs) -> Result<Outcome<Vec<Decision>>> { |
| 262 | let rows = match &a.repo { |
| 263 | Some(path) => { |
| 264 | let (repo, pull) = match self.pull_at(path, a.number, &a.viewer).await? { |
| 265 | Outcome::Ok(found) => found, |
| 266 | Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)), |
| 267 | }; |
| 268 | self.db |
| 269 | .prepare(format!( |
| 270 | "SELECT {DECISION_COLUMNS} FROM decisions WHERE repo_id = ?1 AND pull = ?2 |
| 271 | ORDER BY created_at, id LIMIT ?3" |
| 272 | )) |
| 273 | .bind(&[repo.id.as_str().into(), pull.number.into(), LIST_LIMIT.into()])? |
| 274 | .all() |
| 275 | .await? |
| 276 | .results::<DecisionRow>()? |
| 277 | } |
| 278 | None => { |
| 279 | let held = match self.item_for(&a.viewer, &a.workspace, a.number, Capability::Read).await? { |
| 280 | Outcome::Ok(held) => held, |
| 281 | Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)), |
| 282 | }; |
| 283 | let rows = self |
| 284 | .db |
| 285 | .prepare(format!( |
| 286 | "SELECT {DECISION_COLUMNS} FROM decisions |
| 287 | WHERE item_id = ?1 OR EXISTS (SELECT 1 FROM pulls p |
| 288 | WHERE p.item_id = ?1 AND p.repo_id = decisions.repo_id AND p.number = decisions.pull) |
| 289 | ORDER BY created_at, id LIMIT ?2" |
| 290 | )) |
| 291 | .bind(&[held.item.id.as_str().into(), LIST_LIMIT.into()])? |
| 292 | .all() |
| 293 | .await? |
| 294 | .results::<DecisionRow>()?; |
| 295 | // Those kept in a repository the viewer cannot read stay there. |
| 296 | let mut ids: Vec<String> = rows.iter().map(|row| row.repo_id.clone()).collect(); |
| 297 | ids.sort(); |
| 298 | ids.dedup(); |
| 299 | let readable: Vec<g1t_contracts::repos::Repo> = g1t_kit::call( |
| 300 | &self.repos, |
| 301 | "readable", |
| 302 | &g1t_contracts::repos::ReadableArgs { ids, viewer: a.viewer.clone() }, |
| 303 | ) |
| 304 | .await?; |
| 305 | rows.into_iter().filter(|row| readable.iter().any(|repo| repo.id == row.repo_id)).collect() |
| 306 | } |
| 307 | }; |
| 308 | Ok(Outcome::Ok(rows.into_iter().filter_map(DecisionRow::decision).collect())) |
| 309 | } |
| 310 | |
| 311 | /// Whether a pull request landed through the merge queue. |
| 312 | pub(crate) async fn landed_through_queue(&self, pull_id: &str) -> Result<bool> { |
| 313 | Ok(self |
| 314 | .db |
| 315 | .prepare("SELECT 1 AS value FROM queue_entries WHERE pull_id = ? AND state = 'landed' LIMIT 1") |
| 316 | .bind(&[pull_id.into()])? |
| 317 | .first::<u32>(Some("value")) |
| 318 | .await? |
| 319 | .is_some()) |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | #[cfg(test)] |
| 324 | mod tests { |
| 325 | use super::*; |
| 326 | |
| 327 | #[test] |
| 328 | fn only_claims_are_recorded_by_hand() { |
| 329 | assert!(checked(DecisionKind::Proposal, "Use a trie.", None, None).is_ok()); |
| 330 | assert!(checked(DecisionKind::Fix, "Rebased on #12.", None, None).is_ok()); |
| 331 | for kind in [ |
| 332 | DecisionKind::IntegrationFailure, |
| 333 | DecisionKind::IntegrationPassed, |
| 334 | DecisionKind::Approval, |
| 335 | DecisionKind::Merge, |
| 336 | ] { |
| 337 | assert!(checked(kind, "x", None, None).is_err(), "{kind:?}"); |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | #[test] |
| 342 | fn a_summary_and_object_evidence_are_required() { |
| 343 | assert!(checked(DecisionKind::Note, " ", None, None).is_err()); |
| 344 | let long = "x".repeat(MAX_SUMMARY_CHARS + 1); |
| 345 | assert!(checked(DecisionKind::Note, &long, None, None).is_err()); |
| 346 | assert!(checked(DecisionKind::Note, "ok", Some(&json!([1])), None).is_err()); |
| 347 | let big = json!({ "log": "x".repeat(MAX_EVIDENCE_BYTES) }); |
| 348 | assert!(checked(DecisionKind::Note, "ok", Some(&big), None).is_err()); |
| 349 | let (summary, evidence) = |
| 350 | checked(DecisionKind::Claim, " Fixes the race. ", Some(&json!({ "commit": "abc" })), Some("ses_1")).unwrap(); |
| 351 | assert_eq!(summary, "Fixes the race."); |
| 352 | assert_eq!(evidence["commit"], "abc"); |
| 353 | assert_eq!(checked(DecisionKind::Claim, "x", Some(&Value::Null), None).unwrap().1, json!({})); |
| 354 | } |
| 355 | |
| 356 | #[test] |
| 357 | fn merges_and_approvals_are_as_sure_as_who_made_them() { |
| 358 | let person = User { id: "usr_1".into(), username: "ana".into(), ..User::default() }; |
| 359 | assert_eq!(merge_confidence(false, &person), DecisionConfidence::Approved); |
| 360 | assert_eq!(merge_confidence(true, &person), DecisionConfidence::Tested); |
| 361 | assert_eq!(merge_confidence(false, &User::system("acme")), DecisionConfidence::Tested); |
| 362 | // A merge a repository's auto-merge made, under the id kept for it. |
| 363 | let policy = User { id: "g1t_policy".into(), username: "g1t".into(), ..User::default() }; |
| 364 | assert_eq!(merge_confidence(false, &policy), DecisionConfidence::Tested); |
| 365 | assert_eq!(approval_confidence(&person), DecisionConfidence::Approved); |
| 366 | let agent = User { |
| 367 | kind: g1t_contracts::PrincipalKind::Agent, |
| 368 | ..person.clone() |
| 369 | }; |
| 370 | if g1t_contracts::rules::is_agent(&agent) { |
| 371 | assert_eq!(approval_confidence(&agent), DecisionConfidence::Claimed); |
| 372 | assert_eq!(merge_confidence(false, &agent), DecisionConfidence::Claimed); |
| 373 | } |
| 374 | } |
| 375 | } |