Skip to content
Open
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
54 changes: 50 additions & 4 deletions src/deploy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use crate::github_actions::ProducingRun;
use crate::model::{CommitDeploy, CommitDeployRollback, RollbackDeploy};
use crate::{
FIRST_POLL_SECONDS, LONGEST_POLL_SECONDS, RepositoryArgs, Verdict, connected_repository,
poll_deadline, say, text,
poll_deadline, polled, say, text,
};

const SAME_RUN: &str = "Proofline records the landing of a run's deploy only after the run completes. Read it from a separate workflow: https://proofline.sh/docs/ci/#read-the-checks-from-a-separate-workflow";
Expand Down Expand Up @@ -263,9 +263,10 @@ pub(crate) async fn wait(
let checkpoint = args.until.api_name();
let mut delay = FIRST_POLL_SECONDS;
loop {
let (raw, read) = api
.commit_deploy_verifications(repository_id, commit)
.await?;
let read = api.commit_deploy_verifications(repository_id, commit).await;
let Some((raw, read)) = polled(read, Some(deadline), &mut delay).await? else {
continue;
};
let selected: Vec<&CommitDeploy> = read
.deploys
.iter()
Expand Down Expand Up @@ -916,6 +917,51 @@ mod tests {
}
}

/// A read that fails on Proofline's side mid-wait is read again at the
/// next poll, so one bad gateway does not end an hour-long deploy wait.
/// A refusal still ends it at once.
#[tokio::test(start_paused = true)]
async fn a_failed_read_is_read_again_and_a_refusal_ends_the_wait() {
let waiting = recorded(&[deploy("deploy", &[1], &[], &[])]);
let landed = recorded(&[deploy("deploy", &[1], &["HEALTHY"], &[])]);
for status in [500, 502, 503, 504, 429] {
let failed = (status, json!({ "detail": "unavailable" }));
let (verdict, reads, _) = run(
None,
&["--until", "landing", "--timeout", "30"],
vec![waiting.clone(), failed, landed.clone()],
)
.await;
assert_eq!(verdict.unwrap(), Verdict::Done, "{status}");
assert_eq!(reads, 3, "{status}");
}
let refused = (403, json!({ "detail": "no" }));
let (verdict, reads, _) = run(
None,
&["--until", "landing", "--timeout", "30"],
vec![waiting, refused, landed],
)
.await;
assert!(!unavailable(&verdict.unwrap_err()));
assert_eq!(reads, 2);
}

/// A console that keeps failing ends the wait at `--timeout` as
/// unavailable, not after its first failure and not long past the deadline.
#[tokio::test(start_paused = true)]
async fn a_console_that_keeps_failing_ends_the_wait_at_the_timeout() {
let (verdict, reads, took) = run(
None,
&["--until", "landing", "--timeout", "5"],
vec![(502, json!({ "detail": "bad gateway" }))],
)
.await;
assert!(unavailable(&verdict.unwrap_err()));
assert!(reads > 2, "{reads}");
assert!(took >= Duration::from_secs(300), "{took:?}");
assert!(took < Duration::from_secs(360), "{took:?}");
}

/// The wait reads until the named check is recorded, and a check or a
/// deploy that is still missing at `--timeout` is not established.
#[tokio::test(start_paused = true)]
Expand Down
47 changes: 42 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1225,7 +1225,10 @@ async fn read_review(
) -> anyhow::Result<(serde_json::Value, ReviewDetail, Option<Outcome>)> {
let mut delay = FIRST_POLL_SECONDS;
loop {
let (raw, detail) = api.review(review_id).await?;
let Some((raw, detail)) = polled(api.review(review_id).await, deadline, &mut delay).await?
else {
continue;
};
outcome::same_review(&detail, review_id)?;
if sarif {
sarif::validate_subject(&detail, review_id)?;
Expand Down Expand Up @@ -1345,6 +1348,36 @@ fn unavailable(error: &anyhow::Error) -> bool {
})
}

/// A poll's answer, or `None` once a read that failed on Proofline's side (it
/// could not be reached, failed, or limited the rate past the read's own
/// retries) has been reported and the next poll's pause has passed. One bad
/// gateway must not end a wait that the next read would finish. Without a
/// deadline, or once it has passed, the failure ends the wait as before.
pub(crate) async fn polled<T, E: Into<anyhow::Error>>(
result: Result<T, E>,
deadline: Option<tokio::time::Instant>,
delay: &mut u64,
) -> anyhow::Result<Option<T>> {
let error = match result {
Ok(answer) => return Ok(Some(answer)),
Err(error) => error.into(),
};
let now = tokio::time::Instant::now();
let limited = error.downcast_ref::<ApiError>().and_then(ApiError::status) == Some(429);
let Some(deadline) = deadline.filter(|deadline| now < *deadline) else {
return Err(error);
};
if !unavailable(&error) && !limited {
return Err(error);
}
say(&format!(
"proofline: {error:#}; checking again in {delay} seconds."
));
tokio::time::sleep(Duration::from_secs(*delay).min(deadline - now)).await;
*delay = (*delay * 2).min(LONGEST_POLL_SECONDS);
Ok(None)
}

/// `ci review` once its inputs are read. In GitHub Actions without
/// `PROOFLINE_TOKEN`, the job's signed identity is the credential, and only
/// then, on a `pull_request` event, may the job ask for a review itself.
Expand Down Expand Up @@ -1491,10 +1524,13 @@ async fn wait_for_head_review(
let request_at = started + REQUEST_AFTER;
let mut delay = FIRST_POLL_SECONDS;
loop {
let found = latest(api, repository_id, commit, |item| {
let listed = latest(api, repository_id, commit, |item| {
item.kind == "PULL_REQUEST" && item.head_commit_sha.as_deref() == Some(commit)
})
.await?;
.await;
let Some(found) = polled(listed, Some(deadline), &mut delay).await? else {
continue;
};
if found.is_some() {
return Ok(found);
}
Expand Down Expand Up @@ -2104,7 +2140,8 @@ mod tests {
/// half its lifetime, with a newly issued identity, so the wait reads under the first and
/// completes under the second, and the job still asks for one review. A
/// renewal the console refuses ends the same wait before it asks, as a
/// failure (exit 1); one it cannot serve ends it as unavailable (exit 4).
/// failure (exit 1); one it cannot serve is tried again at each poll and
/// ends the wait at its deadline as unavailable (exit 4).
#[tokio::test(start_paused = true)]
async fn a_wait_renews_its_credential_and_a_refused_renewal_ends_it() {
let reviews = format!("GET /api/v1/organizations/{ORG}/reviews");
Expand Down Expand Up @@ -2147,7 +2184,7 @@ mod tests {
assert_eq!(unavailable(&error), exit_four, "{status}: {error:#}");
assert_eq!(review_requests(&received), 0, "{status}: {received:?}");
let last = received.iter().map(|(_, at, ..)| *at).max().unwrap();
assert!(last < REQUEST_AFTER, "{status}: {last:?}");
assert_eq!(last < REQUEST_AFTER, !exit_four, "{status}: {last:?}");
}
}

Expand Down
75 changes: 75 additions & 0 deletions tests/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,81 @@ async fn findings_timeout_applies_only_to_waiting_and_never_panics() {
}
}

/// A wait reads again after a read that fails on Proofline's side, including
/// a `Retry-After` too long for the read's own retries, and completes with
/// the review. A refusal still ends the wait at once.
#[tokio::test]
async fn a_wait_reads_again_after_a_failed_read_and_stops_at_a_refusal() {
for (status, retry_after, code, reads) in [
(StatusCode::BAD_GATEWAY, None, 0, 2),
(StatusCode::SERVICE_UNAVAILABLE, Some("120"), 0, 2),
(StatusCode::TOO_MANY_REQUESTS, Some("61"), 0, 2),
(StatusCode::UNAUTHORIZED, None, 1, 1),
(StatusCode::NOT_FOUND, None, 1, 1),
] {
let requests = Arc::new(AtomicUsize::new(0));
let observed = Arc::clone(&requests);
let app = Router::new().route(
&format!("/api/v1/organizations/{ORG}/reviews/{SELECTED_REVIEW}"),
get(move || {
let observed = Arc::clone(&observed);
async move {
if observed.fetch_add(1, Ordering::SeqCst) == 0 {
let mut response =
(status, Json(json!({ "title": "unavailable" }))).into_response();
if let Some(seconds) = retry_after {
response.headers_mut().insert(
header::RETRY_AFTER,
header::HeaderValue::from_static(seconds),
);
}
return response;
}
Json(json!({
"id": SELECTED_REVIEW,
"kind": "PULL_REQUEST",
"status": "COMPLETED",
"assessment_count": 1,
"assessments": [{
"id": "0190f3a0-0000-7000-8000-000000000044",
"environment_display_name": "production",
"status": "COMPLETED",
"findings": [],
"checks": { "receipt_recorded": true, "status": "READY", "families": [] },
}],
}))
.into_response()
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let output = cli(
&origin,
&[
"findings",
"--review",
SELECTED_REVIEW,
"--json",
"--wait",
"--timeout",
"30",
],
)
.await;
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(code), "{status}: {stderr}");
assert_eq!(requests.load(Ordering::SeqCst), reads, "{status}");
if code == 0 {
assert!(stderr.contains("checking again"), "{stderr}");
let document: Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(document["outcome"], "COMPLETED");
}
server.abort();
}
}

#[tokio::test]
async fn asynchronous_pull_request_acknowledgment_respects_json_without_polling() {
for existing in [false, true] {
Expand Down