Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions lambda/stuck-run-cleanup/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"review_fix": "review fix round",
"feedback": "feedback round",
"security_fix": "security fix round",
"conflict_fix": "conflict round",
}

_dynamodb = None
Expand Down Expand Up @@ -143,8 +144,8 @@ def round_kind(run, pass_name):
return "ci_fix"
if p == "feedback":
return "feedback"
if p == "security_fix":
return "security_fix"
if p in ("security_fix", "conflict_fix"):
return p
return "review_fix"


Expand Down
25 changes: 25 additions & 0 deletions services/common/src/merge_gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,22 @@ pub const STATE_MERGED: &str = "merged";
pub const STATE_CLOSED: &str = "closed";
/// A new commit arrived; the review of that commit re-arms the gate.
pub const STATE_HEAD_MOVED: &str = "head_moved";
/// The PR conflicts with its base. The gate stops: no poll, no completed
/// check suite and no repeated status edit can clear a conflict. CoderHelm
/// updates its own PR's branch once (a resumable round on the run); the
/// review of the new commit re-arms the gate. Otherwise a person resolves it.
pub const STATE_CONFLICT: &str = "conflict";
/// A person stopped auto-merge (a PR comment or the dashboard). Nothing
/// wakes it, not CI, a review or a new commit; only a person re-arms it.
pub const STATE_STOPPED: &str = "stopped";

/// Whether GitHub's reading of a pull request is a merge conflict with its
/// base: `mergeable` false with `mergeable_state` "dirty". Branch protection
/// and checks GitHub still counts as missing are "blocked", not a conflict.
pub fn is_conflict(pr: &serde_json::Value) -> bool {
pr["mergeable_state"].as_str() == Some("dirty") && pr["mergeable"].as_bool() != Some(true)
}

/// Should a completed check suite on the gate's head re-arm it? Only while
/// the gate is waiting on (or was stopped by) CI or GitHub's merge rules.
pub fn wakes_on_ci(state: &str) -> bool {
Expand Down Expand Up @@ -689,6 +701,19 @@ mod tests {
}
}

/// A conflict is never polled: CI can't clear it. The review of a new
/// commit (the head moves) is what re-arms the gate.
#[test]
fn a_conflict_stops_the_gate_until_a_new_commit() {
assert!(!wakes_on_ci(STATE_CONFLICT));
assert!(wakes_on_review(STATE_CONFLICT));
let pr = |m: serde_json::Value, st: &str| serde_json::json!({"mergeable": m, "mergeable_state": st});
assert!(is_conflict(&pr(serde_json::json!(false), "dirty")));
assert!(!is_conflict(&pr(serde_json::json!(true), "blocked")));
assert!(!is_conflict(&pr(serde_json::json!(false), "blocked")));
assert!(!is_conflict(&pr(serde_json::Value::Null, "unknown")));
}

#[test]
fn a_stopped_gate_wakes_on_nothing() {
// No CI run, review, approval or new commit re-arms a person's stop.
Expand Down
69 changes: 66 additions & 3 deletions services/common/src/plugins/kv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,26 @@ fn rec_of(i: &HashMap<String, AttributeValue>) -> Option<Rec> {
Some(Rec { sk, data, rev })
}

/// The key condition for a query: the whole partition when `prefix` is
/// empty. DynamoDB refuses an empty string as an attribute value ("empty
/// string value. Key: sk"), so `begins_with(sk, "")` can never be sent.
fn key_condition(prefix: &str) -> &'static str {
if prefix.is_empty() {
"pk = :p"
} else {
"pk = :p AND begins_with(sk, :s)"
}
}

/// The values [`key_condition`] names, never an empty string.
fn key_values(pk: &str, prefix: &str) -> HashMap<String, AttributeValue> {
let mut v = HashMap::from([(":p".to_string(), s(pk))]);
if !prefix.is_empty() {
v.insert(":s".to_string(), s(prefix));
}
v
}

#[async_trait::async_trait]
impl Kv for Dynamo {
async fn get(&self, pk: &str, sk: &str) -> Result<Option<Rec>, String> {
Expand Down Expand Up @@ -324,9 +344,8 @@ impl Kv for Dynamo {
.client
.query()
.table_name(&self.table)
.key_condition_expression("pk = :p AND begins_with(sk, :s)")
.expression_attribute_values(":p", s(pk))
.expression_attribute_values(":s", s(prefix))
.key_condition_expression(key_condition(prefix))
.set_expression_attribute_values(Some(key_values(pk, prefix)))
.scan_index_forward(!reverse)
.set_exclusive_start_key(start.take());
if let Some(n) = limit {
Expand Down Expand Up @@ -404,4 +423,48 @@ mod tests {
m.delete("t", "A#1").await.unwrap();
assert_eq!(m.get("t", "A#1").await.unwrap(), None);
}

/// The plugin source poll lists a whole index partition with an empty
/// prefix; the query must name only non-empty values, or DynamoDB
/// refuses it and no source is ever polled.
#[test]
fn an_empty_prefix_queries_the_whole_partition_with_no_empty_value() {
let cond = key_condition("");
assert_eq!(cond, "pk = :p");
let v = key_values(SOURCE_INDEX, "");
assert_eq!(v.len(), 1);
assert!(v
.values()
.all(|a| a.as_s().map(|t| !t.is_empty()).unwrap_or(false)));
for name in v.keys() {
assert!(cond.contains(name.as_str()));
}

let cond = key_condition("team|");
assert!(cond.contains("begins_with(sk, :s)"));
let v = key_values("t", "team|");
assert_eq!(
v.get(":s").and_then(|a| a.as_s().ok()).map(String::as_str),
Some("team|")
);
}

#[tokio::test]
async fn every_source_is_listed_for_the_poll() {
let m = Memory::new();
m.put(SOURCE_INDEX, "t1|a", &json!({}), Expect::Any)
.await
.unwrap();
m.put(SOURCE_INDEX, "t2|b", &json!({}), Expect::Any)
.await
.unwrap();
let all = crate::plugins::source::all(&m).await.unwrap();
assert_eq!(
all,
vec![
("t1".to_string(), "a".to_string()),
("t2".to_string(), "b".to_string())
]
);
}
}
2 changes: 2 additions & 0 deletions services/common/src/review_live.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ pub fn pr_status(review_phase: &str, gate_state: &str) -> PrStatus {
g::STATE_BLOCKED_CI => return st("ci_failing", GROUP_WAITING),
g::STATE_WAITING_APPROVAL => return st("waiting_people", GROUP_WAITING),
g::STATE_DECLINED => return st("merge_blocked", GROUP_WAITING),
g::STATE_CONFLICT => return st("merge_conflict", GROUP_WAITING),
g::STATE_PAUSED => return st("paused", GROUP_WAITING),
// Waits on a person to re-arm it.
g::STATE_STOPPED => return st("stopped", GROUP_WAITING),
Expand Down Expand Up @@ -451,6 +452,7 @@ mod tests {
(g::STATE_BLOCKED_CI, "ci_failing", GROUP_WAITING),
(g::STATE_WAITING_APPROVAL, "waiting_people", GROUP_WAITING),
(g::STATE_DECLINED, "merge_blocked", GROUP_WAITING),
(g::STATE_CONFLICT, "merge_conflict", GROUP_WAITING),
(g::STATE_PAUSED, "paused", GROUP_WAITING),
(g::STATE_STOPPED, "stopped", GROUP_WAITING),
(g::STATE_MERGED, "merged", GROUP_DONE),
Expand Down
8 changes: 8 additions & 0 deletions services/common/src/run_round.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@ pub enum Kind {
/// pull request in a fresh invocation, and the pull request stays a
/// draft until the issues are gone.
SecurityFix,
/// The pull request conflicts with its base and auto-merge stopped on
/// it: CoderHelm merges the base into its own pull request's branch,
/// once (`await_merge`).
Conflict,
}

impl Kind {
Expand All @@ -87,6 +91,7 @@ impl Kind {
Kind::ReviewFix => "review_fix",
Kind::Feedback => "feedback",
Kind::SecurityFix => "security_fix",
Kind::Conflict => "conflict_fix",
}
}

Expand All @@ -96,6 +101,7 @@ impl Kind {
"review_fix" => Some(Kind::ReviewFix),
"feedback" => Some(Kind::Feedback),
"security_fix" => Some(Kind::SecurityFix),
"conflict_fix" => Some(Kind::Conflict),
_ => None,
}
}
Expand All @@ -107,6 +113,7 @@ impl Kind {
"ci_fix" | "test" => Kind::CiFix,
"feedback" => Kind::Feedback,
"security_fix" => Kind::SecurityFix,
"conflict_fix" => Kind::Conflict,
_ => Kind::ReviewFix,
}
}
Expand All @@ -118,6 +125,7 @@ impl Kind {
Kind::ReviewFix => "review fix round",
Kind::Feedback => "feedback round",
Kind::SecurityFix => "security fix round",
Kind::Conflict => "conflict round",
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions services/common/src/run_status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ pub fn ended_by_person(status: &str) -> bool {
ENDED_BY_PERSON.contains(&status)
}

/// The lesson trigger for a person's answer to "why was this closed?" on
/// CoderHelm's PR (the gateway sends it, the worker's lessons read it).
pub const CLOSE_REASON_TRIGGER: &str = "close_reason";

/// The condition that refuses to overwrite a run a person ended, for the
/// status attribute behind `status_name` (`#s`, `#status`). Add its values
/// with [`EndedValues::ended_values`].
Expand Down
9 changes: 9 additions & 0 deletions services/gateway/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,11 @@ async fn main() -> Result<(), Error> {
get(routes::knowledge_tokens::sign_in_apps),
)
.route("/admin/dlq/delete", post(routes::admin::admin_dlq_delete))
// A GitHub installation several teams carry: release the stale links
.route(
"/admin/installations/:installation_id/release-stale",
post(routes::admin::release_stale_installation_links),
)
.route("/admin/beta-signups", get(routes::admin::beta_signups))
.route(
"/admin/beta-signups/invite",
Expand Down Expand Up @@ -503,6 +508,10 @@ async fn main() -> Result<(), Error> {
"/github/installation-status",
get(routes::github::installation_status),
)
.route(
"/github/release-stale-link",
post(routes::github::release_stale_link),
)
.route(
"/notifications",
get(routes::api::get_notification_prefs).put(routes::api::update_notification_prefs),
Expand Down
77 changes: 76 additions & 1 deletion services/gateway/src/routes/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -788,6 +788,28 @@ pub async fn admin_teams(
}
}
}
// Installations several teams carry: who receives their events, and
// which links are stale (a warning on the page, with a way to release).
let links: Vec<(String, u64)> = teams
.iter()
.filter_map(|t| {
t.installation_id
.trim()
.parse::<u64>()
.ok()
.map(|iid| (t.team_id.clone(), iid))
})
.collect();
let mut shared_installations: Vec<Value> = Vec::new();
for (iid, team_ids) in super::installation_owner::shared(&links) {
let owner = super::github_webhook::resolve_team_by_installation(&state, iid).await;
shared_installations.push(json!({
"installation_id": iid,
"owner_team_id": owner,
"stale_team_ids": super::installation_owner::stale_teams(&team_ids, owner.as_deref()),
}));
}
shared_installations.sort_by_key(|v| v["installation_id"].as_u64());
let flat: Vec<Value> = orgs
.iter()
.flat_map(|o| o["teams"].as_array().cloned().unwrap_or_default())
Expand All @@ -797,6 +819,7 @@ pub async fn admin_teams(
"month": month,
"orgs": orgs,
"teams": flat,
"shared_installations": shared_installations,
"counts": {
"teams": teams.len(),
"orgs": orgs.len(),
Expand All @@ -806,6 +829,58 @@ pub async fn admin_teams(
})))
}

#[derive(serde::Deserialize, Default)]
pub struct ReleaseStaleRequest {
/// Say what would be released without changing anything (the default).
#[serde(default = "yes")]
pub dry_run: bool,
}

fn yes() -> bool {
true
}

/// POST /api/admin/installations/:installation_id/release-stale { dry_run }
/// — removes the installation's link from every team that carries it but
/// doesn't own it (platform admins only). The owner keeps its link. A dry
/// run (the default) only lists them.
pub async fn release_stale_installation_links(
State(state): State<Arc<AppState>>,
Extension(claims): Extension<Claims>,
axum::extract::Path(installation_id): axum::extract::Path<u64>,
body: Option<Json<ReleaseStaleRequest>>,
) -> Result<Json<Value>, StatusCode> {
if !is_platform_admin(&claims) {
warn!(email = %claims.email, "Installation link release refused: not a platform admin");
return Err(StatusCode::FORBIDDEN);
}
let dry_run = body.map(|Json(b)| b.dry_run).unwrap_or(true);
let teams =
super::github_webhook::resolve_all_teams_by_installation(&state, installation_id).await;
let owner = super::github_webhook::resolve_team_by_installation(&state, installation_id).await;
let stale = super::installation_owner::stale_teams(&teams, owner.as_deref());
let mut released: Vec<String> = Vec::new();
if !dry_run && owner.is_some() {
for team in &stale {
match super::installation_owner::release_stale(&state, team, installation_id).await {
Ok(true) => released.push(team.clone()),
Ok(false) => {}
Err(e) => {
warn!(team, installation_id, error = %e, "Could not release a stale link")
}
}
}
info!(installation_id, released = ?released, by = %claims.email, "Stale installation links released");
}
Ok(Json(json!({
"installation_id": installation_id,
"owner_team_id": owner,
"stale_team_ids": stale,
"dry_run": dry_run,
"released": released,
})))
}

/// PUT /api/admin/teams/:team_id/flags { plugins } — turns a team's
/// feature flags on or off (platform admins only).
pub async fn set_team_flags(
Expand Down Expand Up @@ -1320,6 +1395,6 @@ mod tests {
);
checked += 1;
}
assert_eq!(checked, 7);
assert_eq!(checked, 8);
}
}
Loading
Loading