diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4ae95c17..1a40b8cf 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -3,7 +3,9 @@ # Cargo.toml files drop `publish = false`, envschema-derive and envschema). # A release happens by itself once CI passes on main with a workspace version (Cargo.toml) that has no release yet, so # a version bump is all it takes and the docs never describe a CLI nobody can download. The cli-version job in ci.yml -# fails when the CLI changed since its last release without a bump. Pushing a v* tag by hand still works too. +# fails when the CLI changed since its last release without a bump. Pushing a vX.Y.Z tag by hand still works too. +# Each release also moves the floating major tag (v0) to it: the docs pin the GitHub Action as @v0, so users get the +# newest action, and through its default `version`, the newest CLI, without editing their workflows. name: Release CLI on: @@ -12,7 +14,7 @@ on: types: [completed] branches: [main] push: - tags: ["v*"] + tags: ["v*.*.*"] permissions: contents: write @@ -97,6 +99,21 @@ jobs: run: | gh release create "${{ needs.version.outputs.tag }}" visualci-*.tar.gz* -R "${{ github.repository }}" \ --target "${{ needs.version.outputs.sha }}" --generate-notes + # The floating major tag (v0) follows the newest release. Created with the workflow's token, so it starts no + # workflow of its own (and the tag trigger above only matches vX.Y.Z). + - env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ needs.version.outputs.tag }} + SHA: ${{ needs.version.outputs.sha }} + REPO: ${{ github.repository }} + run: | + major="${TAG%%.*}" + if gh api "repos/$REPO/git/ref/tags/$major" >/dev/null 2>&1; then + gh api -X PATCH "repos/$REPO/git/refs/tags/$major" -f sha="$SHA" -F force=true >/dev/null + else + gh api -X POST "repos/$REPO/git/refs" -f ref="refs/tags/$major" -f sha="$SHA" >/dev/null + fi + echo "$major now points at $TAG ($SHA)" # snapshot-diff on crates.io (https://crates.io/crates/snapshot-diff), once per version in its Cargo.toml, with # crates.io's trusted publishing: the job trades GitHub's OIDC token for a short-lived crates.io token (configured on diff --git a/AGENTS.md b/AGENTS.md index 9bd24b60..466d8219 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,7 +42,8 @@ design is in `docs/design.md`; read it before changing the architecture, and upd `node scripts/skills.mjs` in `frontend` and commit `skills/`; CI fails when they differ. Bump the version in `.claude-plugin/plugin.json` and `marketplace.json` when a skill changes. - A change to the CLI (crates/visualci-cli or crates/visualci-core) bumps the workspace version in Cargo.toml and - Cargo.lock's visualci-* entries. CI's `cli-version` job fails without the bump; once CI passes on main, the release + Cargo.lock's visualci-* entries, and the version defaults in clients/github-action/action.yml and + clients/circleci-orb/orb.yml. CI's `cli-version` job fails without them; once CI passes on main, the release workflow publishes it. The docs never name a CLI version: they write `{{cli_version}}` (`VISUALCI_VERSION={{cli_version}}`, `github-action@v{{cli_version}}`), which the site build fills in with the newest published release (`frontend/scripts/cli-version.mjs`), so they never pin an old CLI or one nobody can download yet. diff --git a/Cargo.lock b/Cargo.lock index d4a297aa..baca7349 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5026,7 +5026,7 @@ dependencies = [ [[package]] name = "visualci-cli" -version = "0.2.25" +version = "0.2.26" dependencies = [ "anyhow", "base64 0.22.1", @@ -5043,7 +5043,7 @@ dependencies = [ [[package]] name = "visualci-core" -version = "0.2.25" +version = "0.2.26" dependencies = [ "globset", "hex", @@ -5063,7 +5063,7 @@ dependencies = [ [[package]] name = "visualci-renderer" -version = "0.2.25" +version = "0.2.26" dependencies = [ "anyhow", "image", @@ -5078,7 +5078,7 @@ dependencies = [ [[package]] name = "visualci-wasm" -version = "0.2.25" +version = "0.2.26" dependencies = [ "image", "serde", diff --git a/Cargo.toml b/Cargo.toml index 28186e85..e6962071 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ resolver = "3" members = ["crates/*", "app"] [workspace.package] -version = "0.2.25" +version = "0.2.26" edition = "2024" license = "Apache-2.0" repository = "https://github.com/DocSpring/visualci" diff --git a/app/src/config.rs b/app/src/config.rs index 4d497b5c..70e44528 100644 --- a/app/src/config.rs +++ b/app/src/config.rs @@ -539,6 +539,7 @@ pub const OTHER_PROGRAMS: &[&str] = &[ "VISUALCI_BRANCH", "VISUALCI_COMMIT", "VISUALCI_PR", + "VISUALCI_BASE_BRANCH", "VISUALCI_ENVIRONMENT", "VISUALCI_GROUPS", "VISUALCI_CONFIG", diff --git a/clients/circleci-orb/orb.yml b/clients/circleci-orb/orb.yml index 5f6548aa..2d9daaf7 100644 --- a/clients/circleci-orb/orb.yml +++ b/clients/circleci-orb/orb.yml @@ -15,8 +15,8 @@ commands: parameters: version: type: string - default: "0.2.8" - description: The CLI release to install, such as 0.2.8. Pin it, so a new release never changes a build. + default: "0.2.26" + description: The CLI release to install, such as 0.2.26. Pin it, so a new release never changes a build. install-dir: type: string default: $HOME/.local/bin @@ -70,7 +70,7 @@ commands: description: Fail the step when VisualCI can't be reached. By default it only reports. version: type: string - default: "0.2.8" + default: "0.2.26" steps: - install: version: << parameters.version >> @@ -117,7 +117,7 @@ commands: default: false version: type: string - default: "0.2.8" + default: "0.2.26" steps: - install: version: << parameters.version >> @@ -160,7 +160,7 @@ jobs: default: false version: type: string - default: "0.2.8" + default: "0.2.26" steps: - install: version: << parameters.version >> diff --git a/clients/github-action/action.yml b/clients/github-action/action.yml index 2a1dcbec..466ab2eb 100644 --- a/clients/github-action/action.yml +++ b/clients/github-action/action.yml @@ -41,9 +41,11 @@ inputs: required: false default: "false" version: - description: The visualci CLI release to install. Pin it, so a new release never changes a build. + description: > + The visualci CLI release to install. Default: the release this tag of the action came with, so @v0 installs the + newest. Pin it to keep a release from changing a build. required: false - default: "0.2.8" + default: "0.2.26" cli: description: A visualci binary to use instead of installing a release (VisualCI's own CI tests its latest CLI). required: false @@ -118,14 +120,19 @@ runs: HEAD_REPO: ${{ github.event.workflow_run.head_repository.full_name }} HEAD_OWNER: ${{ github.event.workflow_run.head_repository.owner.login }} SAME_REPO_PR: ${{ github.event.workflow_run.pull_requests[0].number }} + SAME_REPO_BASE: ${{ github.event.workflow_run.pull_requests[0].base.ref }} EVENT: ${{ github.event.workflow_run.event }} run: | branch="$HEAD_BRANCH" pr="$SAME_REPO_PR" + base="$SAME_REPO_BASE" if [ "$HEAD_REPO" != "$GITHUB_REPOSITORY" ]; then branch="$HEAD_OWNER:$HEAD_BRANCH" - pr=$(gh api -X GET "repos/$GITHUB_REPOSITORY/pulls" -f state=open -f "head=$HEAD_OWNER:$HEAD_BRANCH" \ - --jq "map(select(.head.sha == \"$HEAD_SHA\")) | .[0].number // empty") + found=$(gh api -X GET "repos/$GITHUB_REPOSITORY/pulls" -f state=open -f "head=$HEAD_OWNER:$HEAD_BRANCH" \ + --jq "map(select(.head.sha == \"$HEAD_SHA\")) | .[0] // empty | \"\\(.number) \\(.base.ref)\"") + pr="${found%% *}" + base="${found#* }" + [ -n "$found" ] || base="" fi if [ "$EVENT" = pull_request ] && [ -z "$pr" ]; then echo "::warning title=VisualCI::No open pull request has commit $HEAD_SHA any more (it was pushed to or closed); sending the build without one." @@ -134,6 +141,7 @@ runs: echo "VISUALCI_COMMIT=$HEAD_SHA" echo "VISUALCI_BRANCH=$branch" echo "VISUALCI_PR=${pr:-false}" + [ -z "$pr" ] || [ -z "$base" ] || echo "VISUALCI_BASE_BRANCH=$base" } >> "$GITHUB_ENV" if git rev-parse --git-dir >/dev/null 2>&1; then ref="$HEAD_SHA" diff --git a/crates/visualci-cli/src/ci.rs b/crates/visualci-cli/src/ci.rs index dba480e0..2947c693 100644 --- a/crates/visualci-cli/src/ci.rs +++ b/crates/visualci-cli/src/ci.rs @@ -3,7 +3,8 @@ //! `VISUALCI_COMMIT`, `VISUALCI_BRANCH` and `VISUALCI_PR` always win. Otherwise the provider is detected from the //! variable it always sets, and only that provider's variables are read, so a stray `GIT_COMMIT` on another system //! can't leak in. On pull requests the head commit and the branch's own name are preferred to the merge commit and -//! the target branch some providers report. +//! the target branch some providers report. The target branch is reported apart, as `base_branch`: a pull request's +//! build compares with what its base branch approved (`VISUALCI_BASE_BRANCH` wins here too). /// What the provider told us. Each field is `None` when it didn't say, and the caller falls back to git. #[derive(Debug, Default, PartialEq, Eq)] @@ -12,6 +13,8 @@ pub struct CiContext { pub commit: Option, pub branch: Option, pub pr_number: Option, + /// The branch a pull request merges into, when the provider says. + pub base_branch: Option, } /// Reads the context from an environment lookup (empty values count as unset) and a reader for files the provider @@ -27,6 +30,8 @@ pub fn detect(env: &dyn Fn(&str) -> Option, read_file: &dyn Fn(&str) -> commit: get("CIRCLE_SHA1"), branch: get("CIRCLE_BRANCH"), pr_number: get("CIRCLE_PULL_REQUEST").and_then(|u| u.rsplit('/').next().and_then(parse_pr)), + // CircleCI doesn't name a pull request's base branch. + base_branch: None, } } else if get("GITHUB_ACTIONS").is_some() { github(&get, read_file) @@ -37,6 +42,7 @@ pub fn detect(env: &dyn Fn(&str) -> Option, read_file: &dyn Fn(&str) -> commit: get("BUILDKITE_COMMIT").filter(|c| c != "HEAD"), branch: get("BUILDKITE_BRANCH"), pr_number: pr(&["BUILDKITE_PULL_REQUEST"]), + base_branch: get("BUILDKITE_PULL_REQUEST_BASE_BRANCH"), } } else if get("GITLAB_CI").is_some() { let branch = first(&["CI_MERGE_REQUEST_SOURCE_BRANCH_NAME", "CI_COMMIT_BRANCH", "CI_COMMIT_REF_NAME"]); @@ -54,6 +60,7 @@ pub fn detect(env: &dyn Fn(&str) -> Option, read_file: &dyn Fn(&str) -> (_, branch) => branch, }, pr_number: pr(&["CI_MERGE_REQUEST_IID"]), + base_branch: get("CI_MERGE_REQUEST_TARGET_BRANCH_NAME"), } } else if get("JENKINS_URL").is_some() || get("JENKINS_HOME").is_some() { CiContext { @@ -63,6 +70,7 @@ pub fn detect(env: &dyn Fn(&str) -> Option, read_file: &dyn Fn(&str) -> branch: first(&["CHANGE_BRANCH", "BRANCH_NAME"]) .or_else(|| get("GIT_BRANCH").map(|b| b.strip_prefix("origin/").map(str::to_string).unwrap_or(b))), pr_number: pr(&["CHANGE_ID"]), + base_branch: get("CHANGE_TARGET"), } } else if get("BITBUCKET_BUILD_NUMBER").is_some() { CiContext { @@ -70,6 +78,7 @@ pub fn detect(env: &dyn Fn(&str) -> Option, read_file: &dyn Fn(&str) -> commit: get("BITBUCKET_COMMIT"), branch: get("BITBUCKET_BRANCH"), pr_number: pr(&["BITBUCKET_PR_ID"]), + base_branch: get("BITBUCKET_PR_DESTINATION_BRANCH"), } } else if get("SEMAPHORE").is_some() { CiContext { @@ -78,6 +87,7 @@ pub fn detect(env: &dyn Fn(&str) -> Option, read_file: &dyn Fn(&str) -> commit: first(&["SEMAPHORE_GIT_PR_SHA", "SEMAPHORE_GIT_SHA"]), branch: first(&["SEMAPHORE_GIT_PR_BRANCH", "SEMAPHORE_GIT_BRANCH"]), pr_number: pr(&["SEMAPHORE_GIT_PR_NUMBER"]), + base_branch: get("SEMAPHORE_GIT_PR_BRANCH").and_then(|_| get("SEMAPHORE_GIT_BRANCH")), } } else if get("TRAVIS").is_some() { CiContext { @@ -86,6 +96,7 @@ pub fn detect(env: &dyn Fn(&str) -> Option, read_file: &dyn Fn(&str) -> commit: first(&["TRAVIS_PULL_REQUEST_SHA", "TRAVIS_COMMIT"]), branch: first(&["TRAVIS_PULL_REQUEST_BRANCH", "TRAVIS_BRANCH"]), pr_number: pr(&["TRAVIS_PULL_REQUEST"]), + base_branch: pr(&["TRAVIS_PULL_REQUEST"]).and_then(|_| get("TRAVIS_BRANCH")), } } else { CiContext::default() @@ -101,6 +112,13 @@ pub fn detect(env: &dyn Fn(&str) -> Option, read_file: &dyn Fn(&str) -> // An explicit value that isn't a number ("false") means no pull request. ctx.pr_number = parse_pr(&p); } + if let Some(b) = get("VISUALCI_BASE_BRANCH") { + ctx.base_branch = Some(b); + } + // No pull request, no base branch: a push build compares along its own history. + if ctx.pr_number.is_none() { + ctx.base_branch = None; + } ctx } @@ -127,6 +145,10 @@ fn github(get: &dyn Fn(&str) -> Option, read_file: &dyn Fn(&str) -> Opti commit: head_sha.or_else(|| get("GITHUB_SHA")), branch: label.or_else(|| get("GITHUB_HEAD_REF")).or_else(|| get("GITHUB_REF_NAME")), pr_number: number, + base_branch: pull + .and_then(|p| p["base"]["ref"].as_str()) + .map(str::to_string) + .or_else(|| get("GITHUB_BASE_REF")), } } @@ -250,7 +272,17 @@ mod tests { } fn ctx(provider: &'static str, commit: &str, branch: &str, pr: Option) -> CiContext { - CiContext { provider: Some(provider), commit: Some(commit.into()), branch: Some(branch.into()), pr_number: pr } + CiContext { + provider: Some(provider), + commit: Some(commit.into()), + branch: Some(branch.into()), + pr_number: pr, + base_branch: None, + } + } + + fn into(base: &str, c: CiContext) -> CiContext { + CiContext { base_branch: Some(base.into()), ..c } } #[test] @@ -293,6 +325,12 @@ mod tests { ]); assert_eq!(c, ctx("circleci", "bbb", "feature", None)); assert_eq!(run(&[("VISUALCI_PR", "9")]).pr_number, Some(9)); + // A base branch only goes with a pull request. + assert_eq!( + run(&[("VISUALCI_PR", "9"), ("VISUALCI_BASE_BRANCH", "release-1")]).base_branch.as_deref(), + Some("release-1") + ); + assert_eq!(run(&[("VISUALCI_PR", "false"), ("VISUALCI_BASE_BRANCH", "release-1")]).base_branch, None); } #[test] @@ -327,11 +365,12 @@ mod tests { ("GITHUB_REF", "refs/pull/7/merge"), ("GITHUB_REF_NAME", "7/merge"), ("GITHUB_HEAD_REF", "feature"), + ("GITHUB_BASE_REF", "main"), ("GITHUB_EVENT_PATH", "/event.json"), ], - &[("/event.json", r#"{"pull_request":{"number":7,"head":{"sha":"head"}}}"#)], + &[("/event.json", r#"{"pull_request":{"number":7,"head":{"sha":"head"},"base":{"ref":"release-1"}}}"#)], ); - assert_eq!(c, ctx("github", "head", "feature", Some(7))); + assert_eq!(c, into("release-1", ctx("github", "head", "feature", Some(7)))); } #[test] @@ -357,8 +396,9 @@ mod tests { ("GITHUB_SHA", "merge"), ("GITHUB_REF", "refs/pull/7/merge"), ("GITHUB_HEAD_REF", "feature"), + ("GITHUB_BASE_REF", "release-1"), ]); - assert_eq!(c, ctx("github", "merge", "feature", Some(7))); + assert_eq!(c, into("release-1", ctx("github", "merge", "feature", Some(7)))); } #[test] @@ -368,8 +408,9 @@ mod tests { ("BUILDKITE_COMMIT", "aaa"), ("BUILDKITE_BRANCH", "feature"), ("BUILDKITE_PULL_REQUEST", "12"), + ("BUILDKITE_PULL_REQUEST_BASE_BRANCH", "main"), ]); - assert_eq!(c, ctx("buildkite", "aaa", "feature", Some(12))); + assert_eq!(c, into("main", ctx("buildkite", "aaa", "feature", Some(12)))); let c = run(&[ ("BUILDKITE", "true"), ("BUILDKITE_COMMIT", "HEAD"), @@ -395,8 +436,9 @@ mod tests { ("CI_MERGE_REQUEST_SOURCE_BRANCH_SHA", "head"), ("CI_MERGE_REQUEST_SOURCE_BRANCH_NAME", "feature"), ("CI_MERGE_REQUEST_IID", "5"), + ("CI_MERGE_REQUEST_TARGET_BRANCH_NAME", "release-1"), ]); - assert_eq!(c, ctx("gitlab", "head", "feature", Some(5))); + assert_eq!(c, into("release-1", ctx("gitlab", "head", "feature", Some(5)))); // From a fork: the fork's branch, named with the fork's path. let c = run(&[ ("GITLAB_CI", "true"), @@ -418,8 +460,9 @@ mod tests { ("BRANCH_NAME", "PR-3"), ("CHANGE_BRANCH", "feature"), ("CHANGE_ID", "3"), + ("CHANGE_TARGET", "main"), ]); - assert_eq!(c, ctx("jenkins", "aaa", "feature", Some(3))); + assert_eq!(c, into("main", ctx("jenkins", "aaa", "feature", Some(3)))); let c = run(&[("JENKINS_HOME", "/var/jenkins"), ("GIT_COMMIT", "aaa"), ("GIT_BRANCH", "origin/main")]); assert_eq!(c, ctx("jenkins", "aaa", "main", None)); } @@ -431,8 +474,9 @@ mod tests { ("BITBUCKET_COMMIT", "aaa"), ("BITBUCKET_BRANCH", "feature"), ("BITBUCKET_PR_ID", "8"), + ("BITBUCKET_PR_DESTINATION_BRANCH", "main"), ]); - assert_eq!(c, ctx("bitbucket", "aaa", "feature", Some(8))); + assert_eq!(c, into("main", ctx("bitbucket", "aaa", "feature", Some(8)))); } #[test] @@ -445,7 +489,7 @@ mod tests { ("SEMAPHORE_GIT_PR_BRANCH", "feature"), ("SEMAPHORE_GIT_PR_NUMBER", "6"), ]); - assert_eq!(c, ctx("semaphore", "head", "feature", Some(6))); + assert_eq!(c, into("main", ctx("semaphore", "head", "feature", Some(6)))); } #[test] @@ -467,6 +511,6 @@ mod tests { ("TRAVIS_PULL_REQUEST_SHA", "head"), ("TRAVIS_PULL_REQUEST_BRANCH", "feature"), ]); - assert_eq!(c, ctx("travis", "head", "feature", Some(11))); + assert_eq!(c, into("main", ctx("travis", "head", "feature", Some(11)))); } } diff --git a/crates/visualci-cli/src/client.rs b/crates/visualci-cli/src/client.rs index 991352ac..893dfc5e 100644 --- a/crates/visualci-cli/src/client.rs +++ b/crates/visualci-cli/src/client.rs @@ -162,23 +162,56 @@ impl Client { fn post(&self, path: &str, body: &serde_json::Value) -> Result { timed( || format!("POST {path}"), - || { - let response = self.authed(self.http.post(format!("{}{path}", self.api_url))).json(body).send()?; - read(response, path) - }, + || self.send_api(path, || self.authed(self.http.post(format!("{}{path}", self.api_url))).json(body)), ) } fn get(&self, path: &str) -> Result { timed( || format!("GET {path}"), - || { - let response = self.authed(self.http.get(format!("{}{path}", self.api_url))).send()?; - read(response, path) - }, + || self.send_api(path, || self.authed(self.http.get(format!("{}{path}", self.api_url)))), ) } + /// Send one API request, trying again while the server can't be reached: a 429, a gateway's 502, 503 or 504 (a + /// deploy restarting the server answers "no healthy upstream", 4 Dec 2026: an upload stopped after six batches + /// and the build never finished), or a connection that failed or timed out. Up to ten tries over about a minute, + /// longer than a deploy takes, waiting as `Retry-After` asks when it does. Every API call is safe to repeat: + /// builds are created with a nonce, snapshots are upserted by name, and finalizing twice answers the build. + fn send_api( + &self, + path: &str, + request: impl Fn() -> reqwest::blocking::RequestBuilder, + ) -> Result { + const TRIES: u32 = 10; + let mut attempt = 1; + loop { + let wait = match request().send() { + Ok(response) if gateway_retryable(response.status()) && attempt < TRIES => { + let wait = jitter(retry_after(&response).unwrap_or_else(|| backoff(attempt))); + eprintln!( + "visualci: {path}: {} (try {attempt} of {TRIES}), trying again in {:.1} s", + response.status(), + wait.as_secs_f64() + ); + wait + } + Ok(response) => return read(response, path), + Err(e) if (e.is_timeout() || e.is_connect()) && attempt < TRIES => { + let wait = jitter(backoff(attempt)); + eprintln!( + "visualci: {path}: {e} (try {attempt} of {TRIES}), trying again in {:.1} s", + wait.as_secs_f64() + ); + wait + } + Err(e) => return Err(e.into()), + }; + std::thread::sleep(wait); + attempt += 1; + } + } + /// The MCP server: `$VISUALCI_MCP_URL`, else the API's URL with its `api.` host renamed `mcp.` (production), else /// the API's own host (a development server answers both). fn mcp_url(&self) -> String { @@ -787,6 +820,7 @@ pub fn git_context() -> serde_json::Value { let branch = ci.branch.or_else(|| git(&["rev-parse", "--abbrev-ref", "HEAD"])).unwrap_or_else(|| "unknown".to_string()); let pr_number = ci.pr_number; + let base_branch = ci.base_branch; let environment = crate::ci::environment(&env, ci.provider, std::env::consts::OS); let environment_info = if environment == "ci" { json!({ @@ -808,7 +842,7 @@ pub fn git_context() -> serde_json::Value { .map(|out| out.lines().map(str::to_string).collect()) .unwrap_or_default(); json!({ - "commit": commit, "branch": branch, "pr_number": pr_number, "parent_commits": parents, + "commit": commit, "branch": branch, "pr_number": pr_number, "base_branch": base_branch, "parent_commits": parents, "environment": environment, "environment_info": environment_info, }) } @@ -911,6 +945,12 @@ fn retryable(status: reqwest::StatusCode) -> bool { status == reqwest::StatusCode::TOO_MANY_REQUESTS || status.is_server_error() } +/// An API answer worth trying again: too many requests, or a gateway that couldn't reach the server (the request +/// never ran). A 500 is the server's own error: trying again won't help. +fn gateway_retryable(status: reqwest::StatusCode) -> bool { + matches!(status.as_u16(), 429 | 502 | 503 | 504) +} + /// How long `Retry-After` (in seconds) asks to wait, at most 30 s. fn retry_after(response: &reqwest::blocking::Response) -> Option { let seconds: u64 = response.headers().get(reqwest::header::RETRY_AFTER)?.to_str().ok()?.trim().parse().ok()?; @@ -968,6 +1008,64 @@ mod tests { (url, seen) } + /// An API server for one test: answers each request with the next status in `statuses`, then 200 with `{}`. + fn flaky_api(statuses: Vec) -> (String, std::sync::Arc) { + use std::io::{BufRead, BufReader, Read, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let seen = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let count = seen.clone(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let mut stream = stream.unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut length = 0; + loop { + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") { + length = v.trim().parse().unwrap(); + } + if line == "\r\n" || line.is_empty() { + break; + } + } + let mut body = vec![0; length]; + reader.read_exact(&mut body).unwrap(); + let n = count.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let status = statuses.get(n).copied().unwrap_or(200); + let body = if status == 200 { "{}" } else { "no healthy upstream" }; + write!( + stream, + "HTTP/1.1 {status} X\r\nretry-after: 0\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", + body.len() + ) + .unwrap(); + } + }); + (url, seen) + } + + #[test] + fn api_calls_try_again_while_a_deploy_has_no_healthy_upstream() { + let (url, seen) = flaky_api(vec![503, 502, 504, 429]); + let answer = api_client(&url).post("/api/v1/builds/b1/snapshots", &json!({"snapshots": []})).unwrap(); + assert_eq!(answer, json!({})); + assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 5); + } + + #[test] + fn api_calls_give_up_after_ten_tries_and_never_retry_a_server_error() { + let (url, seen) = flaky_api(vec![503; 20]); + let error = api_client(&url).get("/api/v1/builds/b1").unwrap_err(); + assert!(error.to_string().contains("503"), "{error}"); + assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 10); + + let (url, seen) = flaky_api(vec![500, 500]); + assert!(api_client(&url).get("/api/v1/builds/b1").is_err()); + assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1); + } + fn client() -> Client { Client { api_url: String::new(), token: String::new(), project: None, http: reqwest::blocking::Client::new() } } diff --git a/frontend/content/docs/ci/other.md b/frontend/content/docs/ci/other.md index c1f211f8..65929ff0 100644 --- a/frontend/content/docs/ci/other.md +++ b/frontend/content/docs/ci/other.md @@ -14,6 +14,7 @@ The CLI runs anywhere it can reach `https://api.visualci.com`. It needs a projec | `VISUALCI_COMMIT` | The commit the files come from. Default: your CI provider's variable (below), then `git rev-parse HEAD`. | | `VISUALCI_BRANCH` | The branch. Default: your CI provider's variable, then `git rev-parse --abbrev-ref HEAD`. | | `VISUALCI_PR` | The pull request number. Default: your CI provider's variable. Set it to `false` for no pull request. | +| `VISUALCI_BASE_BRANCH` | The branch the pull request merges into: the build compares with what that branch approved. Default: your CI provider's variable; sent only with a pull request. Without one, the project's default branch. | | `VISUALCI_ENVIRONMENT` | Where the build runs: `ci`, `local-mac`, `local-linux` or your own name. Screenshots keep a baseline set per environment. Default: `ci` when a CI provider or `CI=true` is detected, else from the OS. | | `VISUALCI_API_URL` | The server, for self-hosting. Default: `https://api.visualci.com`. | diff --git a/scripts/ci/cli_version.sh b/scripts/ci/cli_version.sh index 1a724caa..33f811df 100755 --- a/scripts/ci/cli_version.sh +++ b/scripts/ci/cli_version.sh @@ -2,9 +2,24 @@ # Fails when the CLI (crates/visualci-cli or crates/visualci-core) changed since its last release and the workspace # version in Cargo.toml still names that release. Bump the version (Cargo.toml and Cargo.lock): CI on main then # releases it (.github/workflows/release.yml), so the docs never describe a CLI nobody can download. +# Also fails when the GitHub Action's or the orb's default `version` isn't the workspace version: users pin the action +# as @v0, which the release moves, so its default must install the CLI released with it. set -eu version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1) -last=$(git tag --list 'v[0-9]*' --sort=-version:refname | head -1) +stale=0 +action=$(awk '/^ version:/{f=1} f && /default:/{gsub(/[" ]/,"",$2); print $2; exit}' clients/github-action/action.yml) +if [ "$action" != "$version" ]; then + echo "clients/github-action/action.yml's version default is $action, not the workspace version $version." >&2 + stale=1 +fi +for orb in $(grep -n 'default: "[0-9]*\.[0-9]*\.[0-9]*"' clients/circleci-orb/orb.yml | sed 's/.*default: "\(.*\)"/\1/'); do + if [ "$orb" != "$version" ]; then + echo "clients/circleci-orb/orb.yml has a version default $orb, not the workspace version $version." >&2 + stale=1 + fi +done +[ "$stale" = 0 ] || exit 1 +last=$(git tag --list 'v[0-9]*.[0-9]*.[0-9]*' --sort=-version:refname | head -1) if [ -z "$last" ]; then echo "No CLI release yet; v$version will be the first." exit 0