diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9b545e7..3f89b9e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -115,7 +115,10 @@ jobs: - name: Cache cargo artifacts uses: Swatinem/rust-cache@v2 - - name: Package publishable crates + - name: Test selective release tooling + run: python3 -B -m unittest discover -s scripts -p 'test_publish_crates.py' + + - name: Package crates in the release plan run: scripts/publish-crates.sh --dry-run gate: diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 73cd542..ecf3f16 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -7,18 +7,14 @@ on: workflow_dispatch: inputs: version: - description: Workspace version to publish + description: Release identifier in release.json required: true - default: "0.1.2" + type: string dry_run: description: Run package preflight instead of publishing required: true type: boolean default: true - start_at: - description: Optional crate name to resume from in publish order - required: false - default: "" concurrency: group: publish-crates-${{ github.ref }} @@ -32,7 +28,7 @@ permissions: jobs: publish: - name: Publish crates.io workspace + name: Publish selected crates to crates.io runs-on: ubuntu-latest steps: - name: Checkout @@ -50,7 +46,6 @@ jobs: EVENT_NAME: ${{ github.event_name }} MANUAL_VERSION: ${{ inputs.version }} MANUAL_DRY_RUN: ${{ inputs.dry_run }} - MANUAL_START_AT: ${{ inputs.start_at }} run: | set -euo pipefail @@ -61,63 +56,37 @@ jobs: fi version="${GITHUB_REF#refs/tags/v}" - if [[ ! "$version" =~ ^[0-9]+[.][0-9]+[.][0-9]+([-+][0-9A-Za-z.-]+)?$ ]]; then - echo "release tag must be v; got ${GITHUB_REF}" >&2 - exit 1 - fi - dry_run=false - start_at="" else version="$MANUAL_VERSION" dry_run="${MANUAL_DRY_RUN:-true}" - start_at="$MANUAL_START_AT" + fi + + if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([+-][0-9A-Za-z.+-]+)?$ ]]; then + echo "invalid release version: ${version}" >&2 + exit 1 + fi + if [[ "$dry_run" != "true" && "$GITHUB_REF" != "refs/tags/v${version}" ]]; then + echo "publishing requires the matching v${version} tag" >&2 + exit 1 fi { echo "version=${version}" echo "dry_run=${dry_run}" - echo "start_at=${start_at}" } >> "$GITHUB_OUTPUT" - - name: Verify release inputs - env: - INPUT_VERSION: ${{ steps.release-inputs.outputs.version }} - DRY_RUN: ${{ steps.release-inputs.outputs.dry_run }} - START_AT: ${{ steps.release-inputs.outputs.start_at }} - CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_IO_TOKEN }} - run: | - set -euo pipefail - workspace_version="$(cargo pkgid -p openwire-core | sed 's/.*#//')" - test "$workspace_version" = "$INPUT_VERSION" - - if [[ "$DRY_RUN" != "true" ]]; then - test -n "${CARGO_REGISTRY_TOKEN:-}" - if [[ "${GITHUB_REF}" != "refs/tags/v${INPUT_VERSION}" ]]; then - test -n "$START_AT" - test "${GITHUB_REF}" = "refs/heads/main" - fi - fi - - name: Package preflight if: ${{ steps.release-inputs.outputs.dry_run == 'true' }} env: - START_AT: ${{ steps.release-inputs.outputs.start_at }} - run: | - if [[ -n "$START_AT" ]]; then - scripts/publish-crates.sh --dry-run --start-at "$START_AT" - else - scripts/publish-crates.sh --dry-run - fi + RELEASE_VERSION: ${{ steps.release-inputs.outputs.version }} + run: scripts/publish-crates.sh --dry-run --release "$RELEASE_VERSION" - name: Publish crates if: ${{ steps.release-inputs.outputs.dry_run != 'true' }} env: CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_IO_TOKEN }} - START_AT: ${{ steps.release-inputs.outputs.start_at }} + RELEASE_VERSION: ${{ steps.release-inputs.outputs.version }} run: | - if [[ -n "$START_AT" ]]; then - scripts/publish-crates.sh --publish --start-at "$START_AT" - else - scripts/publish-crates.sh --publish - fi + test -n "$CARGO_REGISTRY_TOKEN" + scripts/publish-crates.sh --publish --release "$RELEASE_VERSION" diff --git a/Cargo.lock b/Cargo.lock index e8cd3d1..917500c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1154,7 +1154,7 @@ checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" [[package]] name = "openwire" -version = "0.1.2" +version = "0.1.3" dependencies = [ "async-compression", "base64", @@ -1196,7 +1196,7 @@ dependencies = [ [[package]] name = "openwire-cache" -version = "0.1.2" +version = "0.1.3" dependencies = [ "async-trait", "bytes", @@ -1212,7 +1212,7 @@ dependencies = [ [[package]] name = "openwire-core" -version = "0.1.2" +version = "0.1.3" dependencies = [ "bytes", "futures-core", @@ -1289,7 +1289,7 @@ dependencies = [ [[package]] name = "openwire-tokio" -version = "0.1.2" +version = "0.1.3" dependencies = [ "hyper", "openwire-core", diff --git a/Cargo.toml b/Cargo.toml index 723c5e5..75c0daf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,6 @@ resolver = "2" [workspace.package] edition = "2021" license = "MIT" -version = "0.1.2" authors = ["OpenWire contributors"] repository = "https://github.com/peterich-rs/openwire" rust-version = "1.80" @@ -38,6 +37,7 @@ http-body = "1.0.1" http-body-util = "0.1.3" httpdate = "1.0.3" hyper = { version = "1.8.1", default-features = false, features = ["client", "http1", "http2"] } +# Shared dependency minima. Members that use newer APIs declare higher minima. openwire = { path = "crates/openwire", version = "0.1.2", default-features = false } openwire-cache = { path = "crates/openwire-cache", version = "0.1.2" } openwire-core = { path = "crates/openwire-core", version = "0.1.2" } diff --git a/README.md b/README.md index 38c88b6..6e2fefc 100644 --- a/README.md +++ b/README.md @@ -77,11 +77,11 @@ keeps the client API and higher-level policy / planning surfaces. ## Installation -The next planned crates.io release is `0.1.2`: +Install the OpenWire client from crates.io: ```toml [dependencies] -openwire = "0.1.2" +openwire = "0.1.3" ``` Default features are `tls-rustls`, `platform-verifier`, `compression` (all @@ -94,7 +94,7 @@ own default feature set through Cargo unification. ```toml [dependencies] -openwire = { version = "0.1.2", default-features = false, features = ["tls-rustls", "gzip"] } +openwire = { version = "0.1.3", default-features = false, features = ["tls-rustls", "gzip"] } ``` Optional features: @@ -110,8 +110,8 @@ Optional features: | `websocket` | no | RFC 6455 WebSocket client | | `multipart` | no | `multipart/form-data` encoder (`Form` / `Part`) | -Optional companion crates are published with the same workspace version, for -example `openwire-cache = "0.1.2"` or `openwire-tungstenite = "0.1.2"`. +Companion crates have independent versions. This release uses +`openwire-cache = "0.1.3"` and `openwire-tungstenite = "0.1.2"`. Release and versioning steps are documented in `docs/release-process.md`. ## Quick Start diff --git a/crates/openwire-cache/Cargo.toml b/crates/openwire-cache/Cargo.toml index 3307aa4..a7cd5da 100644 --- a/crates/openwire-cache/Cargo.toml +++ b/crates/openwire-cache/Cargo.toml @@ -3,7 +3,7 @@ name = "openwire-cache" description = "Application-layer HTTP cache interceptor for OpenWire" edition.workspace = true license.workspace = true -version.workspace = true +version = "0.1.3" authors.workspace = true repository.workspace = true rust-version.workspace = true @@ -16,13 +16,13 @@ async-trait.workspace = true bytes.workspace = true http.workspace = true httpdate.workspace = true -openwire.workspace = true +openwire = { path = "../openwire", version = "0.1.3", default-features = false } tokio = { workspace = true, features = ["sync"] } url.workspace = true [dev-dependencies] hyper.workspace = true -openwire = { workspace = true, default-features = true } +openwire = { path = "../openwire", version = "0.1.3" } openwire-rustls.workspace = true openwire-test.workspace = true tokio = { workspace = true, features = ["rt-multi-thread", "macros", "sync", "net", "time", "io-util"] } diff --git a/crates/openwire-core/Cargo.toml b/crates/openwire-core/Cargo.toml index c448e74..c46ea8e 100644 --- a/crates/openwire-core/Cargo.toml +++ b/crates/openwire-core/Cargo.toml @@ -3,7 +3,7 @@ name = "openwire-core" description = "Shared primitives, policies, bodies, and transport traits for OpenWire" edition.workspace = true license.workspace = true -version.workspace = true +version = "0.1.3" authors.workspace = true repository.workspace = true rust-version.workspace = true diff --git a/crates/openwire-fastwebsockets/Cargo.toml b/crates/openwire-fastwebsockets/Cargo.toml index 90d4d23..4fe5783 100644 --- a/crates/openwire-fastwebsockets/Cargo.toml +++ b/crates/openwire-fastwebsockets/Cargo.toml @@ -3,7 +3,7 @@ name = "openwire-fastwebsockets" description = "fastwebsockets engine adapter for OpenWire WebSocket clients" edition.workspace = true license.workspace = true -version.workspace = true +version = "0.1.2" authors.workspace = true repository.workspace = true rust-version.workspace = true diff --git a/crates/openwire-rustls/Cargo.toml b/crates/openwire-rustls/Cargo.toml index d928840..fef1136 100644 --- a/crates/openwire-rustls/Cargo.toml +++ b/crates/openwire-rustls/Cargo.toml @@ -3,7 +3,7 @@ name = "openwire-rustls" description = "Rustls TLS connector integration for OpenWire" edition.workspace = true license.workspace = true -version.workspace = true +version = "0.1.2" authors.workspace = true repository.workspace = true rust-version.workspace = true diff --git a/crates/openwire-test/Cargo.toml b/crates/openwire-test/Cargo.toml index ea94bd5..d4b86b0 100644 --- a/crates/openwire-test/Cargo.toml +++ b/crates/openwire-test/Cargo.toml @@ -3,7 +3,7 @@ name = "openwire-test" description = "Local test support utilities for the OpenWire workspace" edition.workspace = true license.workspace = true -version.workspace = true +version = "0.1.2" authors.workspace = true repository.workspace = true rust-version.workspace = true diff --git a/crates/openwire-tokio/Cargo.toml b/crates/openwire-tokio/Cargo.toml index dddbe1b..dd514f3 100644 --- a/crates/openwire-tokio/Cargo.toml +++ b/crates/openwire-tokio/Cargo.toml @@ -3,7 +3,7 @@ name = "openwire-tokio" description = "Tokio executor, timer, DNS, TCP, and I/O adapters for OpenWire" edition.workspace = true license.workspace = true -version.workspace = true +version = "0.1.3" authors.workspace = true repository.workspace = true rust-version.workspace = true diff --git a/crates/openwire-tungstenite/Cargo.toml b/crates/openwire-tungstenite/Cargo.toml index a399151..7e8c406 100644 --- a/crates/openwire-tungstenite/Cargo.toml +++ b/crates/openwire-tungstenite/Cargo.toml @@ -3,7 +3,7 @@ name = "openwire-tungstenite" description = "tokio-tungstenite engine adapter for OpenWire WebSocket clients" edition.workspace = true license.workspace = true -version.workspace = true +version = "0.1.2" authors.workspace = true repository.workspace = true rust-version.workspace = true diff --git a/crates/openwire/Cargo.toml b/crates/openwire/Cargo.toml index 8e1b9b3..7572299 100644 --- a/crates/openwire/Cargo.toml +++ b/crates/openwire/Cargo.toml @@ -3,7 +3,7 @@ name = "openwire" description = "OkHttp-inspired async HTTP client for Rust built on hyper and tower" edition.workspace = true license.workspace = true -version.workspace = true +version = "0.1.3" authors.workspace = true repository.workspace = true rust-version.workspace = true @@ -48,8 +48,8 @@ http-body.workspace = true http-body-util.workspace = true httpdate.workspace = true hyper.workspace = true -openwire-core.workspace = true -openwire-tokio.workspace = true +openwire-core = { path = "../openwire-core", version = "0.1.3" } +openwire-tokio = { path = "../openwire-tokio", version = "0.1.3" } getrandom = { workspace = true, optional = true } mime = { version = "0.3", default-features = false, optional = true } openwire-rustls = { workspace = true, optional = true } diff --git a/docs/release-process.md b/docs/release-process.md index 57991e2..fdb4cfa 100644 --- a/docs/release-process.md +++ b/docs/release-process.md @@ -1,115 +1,88 @@ # Release Process -OpenWire publishes the user-facing crates through crates.io so downstream users -can depend on standard registry versions instead of Git source paths. The next -planned release is `0.1.2`. - -## Published Crates - -Publish the workspace crates in dependency order: - -1. `openwire-core` -2. `openwire-tokio` -3. `openwire-rustls` -4. `openwire` -5. `openwire-cache` -6. `openwire-fastwebsockets` -7. `openwire-tungstenite` - -`openwire-test` is local test support and has `publish = false`. Published -crate dev-dependencies that point at `openwire-test` remain path-only so Cargo -does not emit a registry dependency on a non-published crate. - -## Versioning - -All publishable crates use the workspace version from the root -`[workspace.package]` table. The same version must also be set on the internal -workspace dependencies in root `[workspace.dependencies]` so packaged manifests -can resolve each OpenWire crate from crates.io after publication. - -For a version bump: - -1. Update `version` in root `[workspace.package]`. -2. Update the `version = "..."` - fields for `openwire`, `openwire-cache`, `openwire-core`, - `openwire-fastwebsockets`, `openwire-rustls`, `openwire-tokio`, and - `openwire-tungstenite` in root `[workspace.dependencies]`. -3. Update README installation examples and any release notes that name the - version. -4. Run `scripts/publish-crates.sh --dry-run` to verify that package metadata and - internal dependency versions are consistent. - -## Pull Request Preflight - -Run the normal CI gates before publishing: +OpenWire publishes its user-facing crates through crates.io. Each crate declares +its version in its own `Cargo.toml`. `openwire-test` is local test support with +`publish = false`. Its path-only dev-dependencies are omitted by Cargo when it +packages the published crates. + +## Prepare a release PR + +1. Bump the crates whose published code or dependency requirements changed. + Keep the versions of compatible crates that can continue using their published + packages. +2. Update minimum dependency versions where a crate uses newer APIs or behavior. + Shared requirements in `[workspace.dependencies]` are defaults. A member can + declare a higher minimum together with its local `path`. Cargo resolves the + local path in the workspace and uses the version requirement on crates.io. +3. Update `release.json` with the release identifier and the exact versions of + the crates to publish. The identifier determines the Git tag. It belongs to + the release plan and can name a batch of different crate versions. +4. Refresh `Cargo.lock`, README installation examples, and release notes. + +The `v0.1.3` plan publishes `openwire-core`, `openwire-tokio`, `openwire`, and +`openwire-cache` as `0.1.3`. `openwire-rustls`, `openwire-fastwebsockets`, and +`openwire-tungstenite` remain available as `0.1.2`. + +## Verify the release PR + +Use current stable Cargo and Python 3. Run the CI checks and the release preflight +from a clean commit. ```sh cargo fmt --all --check -cargo clippy --workspace --all-targets -- -D warnings -cargo test --workspace --all-targets -scripts/publish-crates.sh --dry-run +cargo clippy --locked --workspace --all-targets -- -D warnings +cargo test --locked --workspace --all-targets +cargo test --locked --workspace --all-targets --all-features +python3 -B -m unittest discover -s scripts -p 'test_publish_crates.py' +scripts/publish-crates.sh --dry-run --release 0.1.3 ``` -The dry-run script is intentionally first-release safe. Cargo requires each -versioned internal dependency to already exist in the registry when generating a -full tarball for dependent crates, so before a staged release it checks package -file lists for every publishable crate and builds the `openwire-core` tarball. -The actual publish command still runs Cargo's full publish verification for each -crate after its dependencies have been published. - -## Publishing - -Set the repository secret `CRATES_IO_TOKEN` to a crates.io API token with -publish permission for all published OpenWire crates. - -After the release PR is merged: - -1. Create and push a release tag that matches the workspace version: +The preflight checks the release identifier and each selected crate version, +then asks Cargo to package and compile the selected crates with all features. +Cargo stages unpublished dependencies from the same batch in a temporary +registry and resolves other dependencies from crates.io. The preflight requires +no publish token. CI uses the current plan in `release.json` automatically. - ```sh - git tag v0.1.2 - git push origin v0.1.2 - ``` +## Publish -2. Pushing the `v0.1.2` tag automatically runs the `Publish Crates` GitHub - Actions workflow as a real publish. +Configure the repository secret `CRATES_IO_TOKEN` with permission to publish +the selected crates. After the release PR merges and CI passes, use the SHA +of the merged release commit in place of `RELEASE_COMMIT_SHA`. -Create the release tag only after the release PR has merged. If the intended tag -already exists on an older commit, delete and recreate it on the release commit -or choose a new version instead. - -For tag pushes, the workflow derives the publish version from -`refs/tags/v` and refuses to publish if it does not match the workspace -version. It publishes crates in dependency order and waits for each version to -become visible through Cargo before publishing the next dependent crate. - -The same workflow can still be run manually with `dry_run=true` on a branch or -tag to execute the package preflight without requiring a crates.io token. +```sh +git fetch origin +git tag -a v0.1.3 RELEASE_COMMIT_SHA -m "OpenWire v0.1.3" +git push origin refs/tags/v0.1.3 +``` -## Resuming a Partial Publish +Pushing the matching tag starts the real `Publish Crates` workflow. The job +validates the plan in that commit, checks the crates.io index for each version, +and passes only pending packages to Cargo. Cargo publishes the batch in +dependency order. The job also checks that each new version becomes visible. -crates.io rate-limits publishing many brand-new crate names in a short window. -If a staged publish fails after some crates have already uploaded, wait until -the time reported by crates.io and rerun `Publish Crates` from `main` with: +The workflow can be run manually with `dry_run=true` and a `version` matching the +plan on the selected branch or tag. A manual publish requires the matching tag. -- `version` set to the same workspace version -- `dry_run=false` -- `start_at` set to the first crate that did not publish +## Resume a partial publish -For example, if the first five `0.1.2` crates published and the rate limit -stopped at `openwire-fastwebsockets`, rerun with -`start_at=openwire-fastwebsockets`. The workflow only allows non-tag publishing -when `start_at` is set and the ref is `main`. +Publishing several crates is incremental. If the workflow fails after some +uploads, resolve the error and rerun the same tag workflow. After rate limiting, +wait until the time reported by crates.io. The rerun skips the exact versions +already visible, then publishes the remaining crates. A yanked version or a +registry lookup failure stops the run with an error. -## Post-Publish Verification +## Verify published packages -After the workflow finishes, verify the registry and downstream install path: +Confirm the four selected versions in the registry, then use an empty directory +to check a downstream install of the new client with its companion crates. ```sh -cargo info openwire@0.1.2 -tmpdir="$(mktemp -d)" -cd "$tmpdir" -cargo init --bin -cargo add openwire@0.1.2 +for crate in openwire-core openwire-tokio openwire openwire-cache; do + cargo info "${crate}@0.1.3" +done +release_check_dir="$(mktemp -d)" +cargo init --bin --name openwire-release-check "$release_check_dir" +cd "$release_check_dir" +cargo add 'openwire@=0.1.3' 'openwire-cache@=0.1.3' 'openwire-tungstenite@=0.1.2' cargo check ``` diff --git a/release.json b/release.json new file mode 100644 index 0000000..9867c78 --- /dev/null +++ b/release.json @@ -0,0 +1,9 @@ +{ + "version": "0.1.3", + "crates": { + "openwire-core": "0.1.3", + "openwire-tokio": "0.1.3", + "openwire": "0.1.3", + "openwire-cache": "0.1.3" + } +} diff --git a/scripts/publish-crates.sh b/scripts/publish-crates.sh index 233d315..8cc4f2c 100755 --- a/scripts/publish-crates.sh +++ b/scripts/publish-crates.sh @@ -1,191 +1,4 @@ #!/usr/bin/env bash set -euo pipefail -usage() { - cat <<'USAGE' -Usage: - scripts/publish-crates.sh --dry-run [--allow-dirty] [--start-at CRATE] - scripts/publish-crates.sh --publish [--allow-dirty] [--no-wait] [--start-at CRATE] - -Options: - --dry-run Run a first-release-safe package preflight. Cargo checks package - file lists for every publishable crate, and builds a tarball for - openwire-core because it has no unpublished internal dependency. - --publish Publish each crate to crates.io in dependency order. - --allow-dirty Pass --allow-dirty through to cargo package/publish. - --no-wait Do not wait for each published crate version to become visible - before publishing the next dependent crate. - --start-at Start at this crate in the publish order. This is for resuming - after a partial staged publish. - -h, --help Show this help text. -USAGE -} - -mode="" -allow_dirty=0 -wait_for_registry=1 -start_at="" - -while [[ $# -gt 0 ]]; do - case "$1" in - --dry-run) - mode="dry-run" - ;; - --publish) - mode="publish" - ;; - --allow-dirty) - allow_dirty=1 - ;; - --no-wait) - wait_for_registry=0 - ;; - --start-at) - if [[ $# -lt 2 ]]; then - echo "--start-at requires a crate name" >&2 - exit 2 - fi - start_at="$2" - shift - ;; - -h | --help) - usage - exit 0 - ;; - *) - echo "unknown argument: $1" >&2 - usage >&2 - exit 2 - ;; - esac - shift -done - -if [[ -z "$mode" ]]; then - echo "missing mode: pass --dry-run or --publish" >&2 - usage >&2 - exit 2 -fi - -readonly publish_order=( - openwire-core - openwire-tokio - openwire-rustls - openwire - openwire-cache - openwire-fastwebsockets - openwire-tungstenite -) - -selected_publish_order=() -if [[ -n "$start_at" ]]; then - found_start=0 - for crate in "${publish_order[@]}"; do - if [[ "$crate" == "$start_at" ]]; then - found_start=1 - fi - if [[ "$found_start" -eq 1 ]]; then - selected_publish_order+=("$crate") - fi - done - if [[ "$found_start" -ne 1 ]]; then - echo "--start-at crate is not in publish order: $start_at" >&2 - exit 2 - fi -else - selected_publish_order=("${publish_order[@]}") -fi - -cargo_package() { - if [[ "$allow_dirty" -eq 1 ]]; then - cargo package "$@" --allow-dirty - else - cargo package "$@" - fi -} - -cargo_publish() { - if [[ "$allow_dirty" -eq 1 ]]; then - cargo publish "$@" --allow-dirty - else - cargo publish "$@" - fi -} - -crate_version() { - cargo pkgid -p "$1" | sed 's/.*#//' -} - -workspace_version="$(crate_version openwire-core)" -for crate in "${publish_order[@]}"; do - version="$(crate_version "$crate")" - if [[ "$version" != "$workspace_version" ]]; then - echo "version mismatch: openwire-core is $workspace_version but $crate is $version" >&2 - exit 1 - fi -done - -assert_internal_dependency_versions_match() { - local dependency - local expected="version = \"$workspace_version\"" - - for dependency in \ - openwire \ - openwire-cache \ - openwire-core \ - openwire-fastwebsockets \ - openwire-rustls \ - openwire-tokio \ - openwire-tungstenite - do - if ! grep -Fq "$dependency = {" Cargo.toml; then - echo "missing workspace dependency entry for $dependency" >&2 - exit 1 - fi - if ! grep -F "$dependency = {" Cargo.toml | grep -Fq "$expected"; then - echo "workspace dependency $dependency must use $expected" >&2 - exit 1 - fi - done -} - -wait_until_visible() { - local crate="$1" - local version="$2" - local attempt - - for attempt in {1..30}; do - if cargo info "${crate}@${version}" >/dev/null 2>&1; then - return 0 - fi - echo "waiting for ${crate} ${version} to become visible on crates.io (${attempt}/30)" - sleep 10 - done - - echo "${crate} ${version} was not visible on crates.io after waiting" >&2 - return 1 -} - -assert_internal_dependency_versions_match - -echo "OpenWire release version: ${workspace_version}" -if [[ -n "$start_at" ]]; then - echo "Starting at crate: ${start_at}" -fi - -for crate in "${selected_publish_order[@]}"; do - echo "==> ${mode}: ${crate}" - if [[ "$mode" == "dry-run" ]]; then - cargo_package -p "$crate" --list >/dev/null - if [[ "$crate" == "openwire-core" ]]; then - cargo_package -p "$crate" --no-verify - else - echo "checked package file list; tarball packaging waits for staged registry dependencies" - fi - else - cargo_publish -p "$crate" - if [[ "$wait_for_registry" -eq 1 ]]; then - wait_until_visible "$crate" "$workspace_version" - fi - fi -done +exec python3 "$(dirname "${BASH_SOURCE[0]}")/publish_crates.py" "$@" diff --git a/scripts/publish_crates.py b/scripts/publish_crates.py new file mode 100644 index 0000000..7d1d9da --- /dev/null +++ b/scripts/publish_crates.py @@ -0,0 +1,179 @@ +import argparse +import json +import re +import subprocess +import sys +import time +from pathlib import Path +from urllib.error import HTTPError, URLError +from urllib.request import Request, urlopen + + +ROOT = Path(__file__).resolve().parent.parent +RELEASE_VERSION = re.compile( + r"(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)" + r"(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?" + r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?" +) + + +class ReleaseError(Exception): + pass + + +def publishable_packages(): + result = subprocess.run( + ["cargo", "metadata", "--no-deps", "--format-version", "1", "--locked"], + cwd=ROOT, + check=True, + stdout=subprocess.PIPE, + ) + return { + package["name"]: package["version"] + for package in json.loads(result.stdout)["packages"] + if package["publish"] is None or "crates-io" in package["publish"] + } + + +def unique_fields(pairs): + fields = {} + for name, value in pairs: + if name in fields: + raise ReleaseError(f"duplicate release plan field {name!r}") + fields[name] = value + return fields + + +def read_release(path, requested_version, packages): + with path.open(encoding="utf-8") as handle: + plan = json.load(handle, object_pairs_hook=unique_fields) + if not isinstance(plan, dict) or plan.keys() != {"version", "crates"}: + raise ReleaseError(f"{path.name} must contain version and crates") + + release_version = plan["version"] + if not isinstance(release_version, str) or not RELEASE_VERSION.fullmatch(release_version): + raise ReleaseError(f"invalid release version in {path.name}") + if requested_version is not None and requested_version != release_version: + raise ReleaseError(f"requested release {requested_version!r} has no plan in {path.name}") + + selection = plan["crates"] + if not isinstance(selection, dict) or not selection: + raise ReleaseError(f"{path.name} must select at least one crate") + for name, version in selection.items(): + if name not in packages: + raise ReleaseError(f"{name} is not a crates.io publishable workspace crate") + if version != packages[name]: + raise ReleaseError(f"{name} plan selects {version!r}, workspace has {packages[name]}") + return release_version, selection + + +def index_path(name): + name = name.lower() + if len(name) <= 2: + return f"{len(name)}/{name}" + if len(name) == 3: + return f"3/{name[0]}/{name}" + return f"{name[:2]}/{name[2:4]}/{name}" + + +def registry_version_exists(name, version): + request = Request( + f"https://index.crates.io/{index_path(name)}", + headers={"User-Agent": "OpenWire release tooling", "Cache-Control": "no-cache"}, + ) + try: + with urlopen(request, timeout=30) as response: + entries = [json.loads(line) for line in response if line.strip()] + except HTTPError as error: + if error.code in (404, 410): + return False + raise ReleaseError(f"crates.io index lookup failed for {name}: HTTP {error.code}") from error + except (URLError, OSError, ValueError) as error: + raise ReleaseError(f"crates.io index lookup failed for {name}: {error}") from error + + if not entries or any( + not isinstance(entry, dict) + or entry.get("name") != name + or not isinstance(entry.get("vers"), str) + or not isinstance(entry.get("yanked"), bool) + for entry in entries + ): + raise ReleaseError(f"invalid crates.io index entry for {name}") + + for entry in entries: + published_version = entry["vers"] + if published_version.partition("+")[0] != version.partition("+")[0]: + continue + if published_version != version: + raise ReleaseError(f"{name}@{published_version} occupies {name}@{version} on crates.io") + if entry["yanked"]: + raise ReleaseError(f"{name}@{version} is yanked on crates.io") + return True + return False + + +def pending_packages(selection): + pending = {} + for name, version in selection.items(): + if registry_version_exists(name, version): + print(f"Already published: {name}@{version}", flush=True) + else: + pending[name] = version + return pending + + +def run_cargo(command, selection, allow_dirty): + args = ["cargo", command, "--locked", "--registry", "crates-io"] + if command == "package": + args.append("--all-features") + if allow_dirty: + args.append("--allow-dirty") + for name, version in selection.items(): + args.extend(["-p", f"{name}@{version}"]) + subprocess.run(args, cwd=ROOT, check=True) + + +def verify_visibility(selection): + waiting = selection + for _ in range(12): + waiting = { + name: version + for name, version in waiting.items() + if not registry_version_exists(name, version) + } + if not waiting: + return + time.sleep(5) + versions = ", ".join(f"{name}@{version}" for name, version in waiting.items()) + raise ReleaseError(f"crates.io index has not picked up {versions}; rerun this release after it updates") + + +def main(): + parser = argparse.ArgumentParser(description="Package or publish the batch in release.json.") + mode = parser.add_mutually_exclusive_group(required=True) + mode.add_argument("--dry-run", action="store_true", help="package and verify without uploading") + mode.add_argument("--publish", action="store_true", help="upload pending versions to crates.io") + parser.add_argument("--release", help="release identifier from the Git tag, without the v prefix") + parser.add_argument("--allow-dirty", action="store_true", help="allow modified package files") + args = parser.parse_args() + if args.publish and args.release is None: + parser.error("--publish requires --release") + + release_version, selection = read_release(ROOT / "release.json", args.release, publishable_packages()) + print(f"OpenWire release {release_version}", flush=True) + if args.dry_run: + run_cargo("package", selection, args.allow_dirty) + else: + pending = pending_packages(selection) + if pending: + run_cargo("publish", pending, args.allow_dirty) + verify_visibility(pending) + else: + print("All planned versions are already published.", flush=True) + + +if __name__ == "__main__": + try: + main() + except (ReleaseError, OSError, json.JSONDecodeError, subprocess.CalledProcessError) as error: + sys.exit(str(error)) diff --git a/scripts/test_publish_crates.py b/scripts/test_publish_crates.py new file mode 100644 index 0000000..252d7ec --- /dev/null +++ b/scripts/test_publish_crates.py @@ -0,0 +1,120 @@ +import json +import sys +import tempfile +import unittest +from io import BytesIO +from pathlib import Path +from unittest.mock import patch +from urllib.error import HTTPError, URLError + +import publish_crates as release + + +CORE = "openwire-core" +TOKIO = "openwire-tokio" +RUSTLS = "openwire-rustls" +SELECTION = {CORE: "0.1.3", TOKIO: "0.1.3"} + + +class ReleasePlanTests(unittest.TestCase): + def read_plan(self, contents, version="0.1.3"): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "release.json" + path.write_text(contents, encoding="utf-8") + return release.read_release(path, version, {**SELECTION, RUSTLS: "0.1.2"}) + + def test_manifest_selects_a_subset_with_exact_versions(self): + selection = {CORE: "0.1.3", RUSTLS: "0.1.2"} + result = self.read_plan(json.dumps({"version": "0.1.3", "crates": selection})) + self.assertEqual(result, ("0.1.3", selection)) + + def test_wrong_tag_or_selection_fails(self): + with self.assertRaisesRegex(release.ReleaseError, "has no plan"): + self.read_plan(json.dumps({"version": "0.1.3", "crates": SELECTION}), "0.1.2") + for selection, message in [ + ({CORE: "0.1.2"}, "workspace has 0.1.3"), + ({"openwire-test": "0.1.2"}, "not a crates.io publishable"), + ({}, "select at least one"), + ]: + with self.subTest(selection=selection), self.assertRaisesRegex(release.ReleaseError, message): + self.read_plan(json.dumps({"version": "0.1.3", "crates": selection})) + + def test_duplicate_entries_fail(self): + with self.assertRaisesRegex(release.ReleaseError, "duplicate release plan field"): + self.read_plan('{"version":"0.1.3","crates":{"openwire-core":"0.1.2","openwire-core":"0.1.3"}}') + + +class RegistryTests(unittest.TestCase): + @patch.object(release, "urlopen") + def test_index_requires_an_exact_version_and_rejects_yanks(self, open_url): + def response(yanked): + return BytesIO((json.dumps({"name": CORE, "vers": "0.1.3", "yanked": yanked}) + "\n").encode()) + + open_url.side_effect = [response(False), response(False), response(True), response(False)] + self.assertFalse(release.registry_version_exists(CORE, "0.1.2")) + self.assertTrue(release.registry_version_exists(CORE, "0.1.3")) + self.assertEqual(open_url.call_args.args[0].full_url, "https://index.crates.io/op/en/openwire-core") + with self.assertRaisesRegex(release.ReleaseError, "is yanked"): + release.registry_version_exists(CORE, "0.1.3") + with self.assertRaisesRegex(release.ReleaseError, "occupies"): + release.registry_version_exists(CORE, "0.1.3+local") + + @patch.object(release, "urlopen") + def test_missing_and_unavailable_registry_have_different_outcomes(self, open_url): + for status in (404, 410, 429, 503): + open_url.side_effect = HTTPError("https://index.crates.io", status, "", {}, None) + if status in (404, 410): + self.assertFalse(release.registry_version_exists(CORE, "0.1.3")) + else: + with self.assertRaisesRegex(release.ReleaseError, f"HTTP {status}"): + release.registry_version_exists(CORE, "0.1.3") + open_url.side_effect = URLError("offline") + with self.assertRaisesRegex(release.ReleaseError, "offline"): + release.registry_version_exists(CORE, "0.1.3") + + @patch.object(release, "urlopen", return_value=BytesIO(b'{"name":"openwire-core"}\n')) + def test_malformed_index_record_fails(self, _open_url): + with self.assertRaisesRegex(release.ReleaseError, "invalid crates.io index entry"): + release.registry_version_exists(CORE, "0.1.3") + + +class ReleaseCommandTests(unittest.TestCase): + @patch.object(release, "read_release", return_value=("0.1.3", SELECTION)) + @patch.object(release, "publishable_packages", return_value=SELECTION) + @patch.object(release, "registry_version_exists") + @patch.object(release.subprocess, "run") + def test_ci_packages_selected_crates_without_uploading(self, run, lookup, _packages, _plan): + with patch.object(sys, "argv", ["publish_crates.py", "--dry-run"]): + release.main() + lookup.assert_not_called() + run.assert_called_once_with( + ["cargo", "package", "--locked", "--registry", "crates-io", "--all-features", + "-p", f"{CORE}@0.1.3", "-p", f"{TOKIO}@0.1.3"], + cwd=release.ROOT, + check=True, + ) + + @patch.object(release, "read_release", return_value=("0.1.3", SELECTION)) + @patch.object(release, "publishable_packages", return_value=SELECTION) + @patch.object(release, "registry_version_exists", side_effect=[True, False, False, True]) + @patch.object(release.time, "sleep") + @patch.object(release.subprocess, "run") + def test_retry_uploads_only_missing_versions_and_verifies_visibility(self, run, sleep, lookup, _packages, _plan): + with patch.object(sys, "argv", ["publish_crates.py", "--publish", "--release", "0.1.3"]): + release.main() + run.assert_called_once_with( + ["cargo", "publish", "--locked", "--registry", "crates-io", "-p", f"{TOKIO}@0.1.3"], + cwd=release.ROOT, + check=True, + ) + self.assertEqual(lookup.call_args_list[-1].args, (TOKIO, "0.1.3")) + sleep.assert_called_once_with(5) + + @patch.object(release, "read_release", return_value=("0.1.3", SELECTION)) + @patch.object(release, "publishable_packages", return_value=SELECTION) + @patch.object(release, "registry_version_exists", return_value=True) + @patch.object(release.subprocess, "run") + def test_completed_release_is_a_no_op(self, run, _lookup, _packages, _plan): + with patch.object(sys, "argv", ["publish_crates.py", "--publish", "--release", "0.1.3"]): + release.main() + run.assert_not_called()