Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

ci(android): publish Play releases from main's copy of the workflows (#9563)

Peter Chinmanf4db42d8ea61
diff --git a/.github/workflows/android-play-publish.yml b/.github/workflows/android-play-publish.yml
new file mode 100644
index 0000000000..91afa8c42c
--- /dev/null
+++ b/.github/workflows/android-play-publish.yml
@@ -0,0 +1,854 @@
+# DO NOT EDIT — regenerate with `cargo x workflows` (from the repository root).
+# Source: tooling/xtask/crates/xtask_workflows/src/workflows/android_play_publish.rs
+name: Android Play Publish
+'on':
+ workflow_run:
+ types:
+ - completed
+ workflows:
+ - Android Play Release
+jobs:
+ check:
+ if: github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.head_repository.full_name == github.repository
+ name: Check the release request
+ runs-on: namespace-profile-linux-tiny-no-cache
+ permissions:
+ actions: read
+ contents: read
+ issues: read
+ pull-requests: write
+ outputs:
+ publish: ${{ steps.verify.outputs.publish }}
+ pr_number: ${{ steps.verify.outputs.pr_number }}
+ version_code: ${{ steps.verify.outputs.version_code }}
+ release_name: ${{ steps.verify.outputs.release_name }}
+ env:
+ GH_TOKEN: ${{ github.token }}
+ GH_REPO: ${{ github.repository }}
+ timeout-minutes: 10
+ steps:
+ - name: Checkout
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd
+ with:
+ clean: 'false'
+ persist-credentials: 'false'
+ - name: Setup Bun
+ uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6
+ with:
+ bun-version: '1.3.13'
+ - id: verify
+ name: Require a build the android-update label started
+ run: |
+ printf '%s\n' "$LOGGED_STEP" > "$RUNNER_TEMP/last-step.name"
+ exec > >(tee "$RUNNER_TEMP/last-step.log") 2>&1
+ # --- authenticated fetch ------------------------------------------------------
+ # gh_fetch <sha|ref>: make a commit that is not in this checkout (the base
+ # commit, a moved PR head, GitHub's test merge commit) available. Checkouts
+ # may persist credentials, so clear inherited headers before supplying one
+ # explicitly. Keep Nix build libraries out of the host Git HTTPS helper.
+ # Fails if the commit is unreachable (a force-pushed-away head).
+ gh_fetch() {
+ local auth
+ auth=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 | tr -d '\n')
+ LD_LIBRARY_PATH= git -c "http.https://github.com/.extraheader=" \
+ -c "http.https://github.com/.extraheader=AUTHORIZATION: basic ${auth}" \
+ fetch -q --depth=1 origin "$1"
+ }
+ # ------------------------------------------------------------------------------
+ set -euo pipefail
+ # Android Play Publish runs main's copy for every completed Android Play
+ # Release run. That run executed the PR's own copy of the workflow, so its
+ # name, artifact and outcome prove nothing on their own: any PR can add a
+ # workflow named "Android Play Release" that runs on any event. The
+ # `android-update` label is the release decision, so publish only a build
+ # tied to the person who added it, checking GitHub's records rather than
+ # the run's:
+ #
+ # 1. it ran the release workflow file and its release job succeeded;
+ # 2. its branch is the head of exactly one open same-repository PR into main;
+ # 3. that PR still carries the label, and the label's latest event is an
+ # add by a person (not a bot or token) with write access;
+ # 4. that person started this run, within minutes of adding the label, so
+ # a run from before a newer add, or from much later, does not qualify.
+ #
+ # This binds the build to that person, not to the label event itself: GitHub
+ # doesn't record which activity created a run, and the branch's own copy of
+ # the release workflow decides which activities build. A branch that edits
+ # that workflow could also build on the person's other PR activity inside
+ # the window, after a push they did not review. That gives nobody more than
+ # adding the label already does: pushing to a same-repository branch needs
+ # write access, which is all adding the label needs.
+ #
+ # The head guard (a later step) then checks the PR's native code is still the
+ # built one. Needs GH_TOKEN, GH_REPO, RUN_ID, RUN_ATTEMPT, RUN_PATH,
+ # RUN_ACTOR, RUN_CREATED_AT, HEAD_SHA, HEAD_BRANCH, and gh_fetch.
+ skip() {
+ echo "$1"
+ echo "publish=false" >> "$GITHUB_OUTPUT"
+ exit 0
+ }
+ refuse() {
+ echo "Not publishing run ${RUN_ID}: $1" >&2
+ exit 1
+ }
+
+ if [[ "${RUN_PATH%%@*}" != .github/workflows/android-play-release.yml ]]; then
+ skip "Run ${RUN_ID} ran ${RUN_PATH}, not the Android Play Release workflow file; nothing to publish."
+ fi
+ build=$(gh api "repos/${GH_REPO}/actions/runs/${RUN_ID}/attempts/${RUN_ATTEMPT}/jobs" \
+ --jq '[.jobs[] | select(.name == "Android Play Release") | .conclusion] | first // ""')
+ if [[ "$build" != success ]]; then
+ skip "Run ${RUN_ID}'s Android Play Release job did not succeed (${build:-absent}): another label, or a failed build. Nothing to publish."
+ fi
+
+ pr=$(gh pr list --repo "$GH_REPO" --head "$HEAD_BRANCH" --base main --state open \
+ --json number,isCrossRepository \
+ --jq '[.[] | select(.isCrossRepository == false)] | if length == 1 then .[0].number else "" end')
+ if [[ -z "$pr" ]]; then
+ refuse "branch ${HEAD_BRANCH} is not the head of exactly one open same-repository PR into main."
+ fi
+ export PR_NUMBER=$pr
+ echo "pr_number=${PR_NUMBER}" >> "$GITHUB_OUTPUT"
+ echo "Run ${RUN_ID} built ${HEAD_SHA:0:10} for PR #${PR_NUMBER}."
+
+ if [[ "$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json labels \
+ --jq 'any(.labels[]; .name == "android-update")')" != true ]]; then
+ refuse "PR #${PR_NUMBER} no longer carries the android-update label."
+ fi
+ event=$(gh api --paginate "repos/${GH_REPO}/issues/${PR_NUMBER}/events" \
+ --jq '.[] | select((.event == "labeled" or .event == "unlabeled") and .label.name == "android-update")
+ | {event, login: .actor.login, type: .actor.type, at: .created_at}' \
+ | jq -cs 'sort_by(.at) | last // empty')
+ if [[ -z "$event" ]]; then
+ refuse "PR #${PR_NUMBER} has no android-update label event."
+ fi
+ kind=$(jq -r '.event' <<<"$event")
+ login=$(jq -r '.login' <<<"$event")
+ type=$(jq -r '.type' <<<"$event")
+ at=$(jq -r '.at' <<<"$event")
+ if [[ "$kind" != labeled ]]; then
+ refuse "the android-update label was last removed (${at}), not added."
+ fi
+ if [[ "$type" != User ]]; then
+ refuse "the android-update label was last added by ${login} (${type}); a person with write access must add it."
+ fi
+ if [[ "$login" != "$RUN_ACTOR" ]]; then
+ refuse "${login} added the android-update label last, but ${RUN_ACTOR} started this run, so this is not the run that label started."
+ fi
+ permission=$(gh api "repos/${GH_REPO}/collaborators/${login}/permission" --jq '.permission')
+ if [[ "$permission" != admin && "$permission" != write ]]; then
+ refuse "${login}, who added the android-update label, has ${permission} access; releasing needs write access."
+ fi
+ label_epoch=$(jq -rn --arg t "$at" '$t | fromdateiso8601')
+ run_epoch=$(jq -rn --arg t "$RUN_CREATED_AT" '$t | fromdateiso8601')
+ if (( run_epoch < label_epoch - 60 || run_epoch > label_epoch + 600 )); then
+ refuse "this run was created at ${RUN_CREATED_AT}, but the android-update label was last added at ${at}, so the label did not start it. Re-add the label to release the PR's current head."
+ fi
+ echo "${login} (${permission} access) added android-update at ${at} and started this run at ${RUN_CREATED_AT}."
+
+ gh_fetch "$HEAD_SHA"
+ version_code=$(bun scripts/android-native.mjs version-code "$HEAD_SHA")
+ version=$(git show "${HEAD_SHA}:apps/web/tauri/src-tauri/tauri.android.conf.json" | jq -r '.version')
+ {
+ echo "version_code=${version_code}"
+ echo "release_name=${version} (${version_code})"
+ echo "publish=true"
+ } >> "$GITHUB_OUTPUT"
+ echo "Publishing Android ${version} (version code ${version_code})."
+ shell: bash
+ env:
+ LOGGED_STEP: Require a build the android-update label started
+ RUN_ID: ${{ github.event.workflow_run.id }}
+ RUN_ATTEMPT: ${{ github.event.workflow_run.run_attempt }}
+ RUN_PATH: ${{ github.event.workflow_run.path }}
+ RUN_ACTOR: ${{ github.event.workflow_run.actor.login }}
+ RUN_CREATED_AT: ${{ github.event.workflow_run.created_at }}
+ HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
+ HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
+ working-directory: apps/web
+ - name: Comment on the PR
+ if: failure() && steps.verify.outputs.pr_number != ''
+ run: |
+ set -euo pipefail
+ reason=$(sed -n 's/\x1b\[[0-9;]*m//g; s/^Not publishing run [0-9]*: //p' "$RUNNER_TEMP/last-step.log" | tail -n 1)
+ gh pr comment "$PR_NUMBER" --repo "$GH_REPO" --body "🤖 Android Play Publish did not publish [this Android Play Release build](${BUILD_URL}): ${reason:-see the [workflow run](${RUN_URL}).}
+
+ A person with write access can remove and re-add the \`android-update\` label to release the PR's current head."
+ shell: bash
+ env:
+ PR_NUMBER: ${{ steps.verify.outputs.pr_number }}
+ BUILD_URL: ${{ github.event.workflow_run.html_url }}
+ RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
+ publish:
+ needs:
+ - check
+ if: needs.check.outputs.publish == 'true'
+ name: Android Play Publish
+ runs-on: ubuntu-24.04
+ permissions:
+ actions: read
+ contents: read
+ pull-requests: write
+ statuses: write
+ id-token: write
+ concurrency:
+ group: android-play-publish-${{ github.event.workflow_run.head_branch }}
+ env:
+ GH_TOKEN: ${{ github.token }}
+ GH_REPO: ${{ github.repository }}
+ PR_NUMBER: ${{ needs.check.outputs.pr_number }}
+ VERSION_CODE: ${{ needs.check.outputs.version_code }}
+ BUILT_SHA: ${{ github.event.workflow_run.head_sha }}
+ BASE_BRANCH: main
+ timeout-minutes: 30
+ steps:
+ - name: Checkout
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd
+ with:
+ clean: 'false'
+ persist-credentials: 'false'
+ - name: Setup Bun
+ uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6
+ with:
+ bun-version: '1.3.13'
+ - name: Require the PR's Android native code to be unchanged since the build
+ run: |
+ printf '%s\n' "$LOGGED_STEP" > "$RUNNER_TEMP/last-step.name"
+ exec > >(tee "$RUNNER_TEMP/last-step.log") 2>&1
+ # --- authenticated fetch ------------------------------------------------------
+ # gh_fetch <sha|ref>: make a commit that is not in this checkout (the base
+ # commit, a moved PR head, GitHub's test merge commit) available. Checkouts
+ # may persist credentials, so clear inherited headers before supplying one
+ # explicitly. Keep Nix build libraries out of the host Git HTTPS helper.
+ # Fails if the commit is unreachable (a force-pushed-away head).
+ gh_fetch() {
+ local auth
+ auth=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 | tr -d '\n')
+ LD_LIBRARY_PATH= git -c "http.https://github.com/.extraheader=" \
+ -c "http.https://github.com/.extraheader=AUTHORIZATION: basic ${auth}" \
+ fetch -q --depth=1 origin "$1"
+ }
+ # ------------------------------------------------------------------------------
+ # --- PR merge result ----------------------------------------------------------
+ # pr_merge_commit: print the sha of GitHub's test merge commit for $PR_NUMBER —
+ # the merge result the native gates hash. GitHub computes it lazily
+ # (mergeable=UNKNOWN until it has), so poll a little; a PR that really
+ # conflicts with its base cannot merge anyway. Needs GH_TOKEN, GH_REPO,
+ # PR_NUMBER. Progress goes to stderr so `merge=$(pr_merge_commit)` works.
+ pr_merge_commit() {
+ local deadline pr_json mergeable merge
+ deadline=$(( $(date +%s) + 120 ))
+ while true; do
+ pr_json=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json mergeable,potentialMergeCommit)
+ mergeable=$(jq -r '.mergeable' <<<"$pr_json")
+ merge=$(jq -r '.potentialMergeCommit.oid // empty' <<<"$pr_json")
+ if [[ -n "$merge" ]]; then
+ echo "$merge"
+ return 0
+ fi
+ if [[ "$mergeable" == "CONFLICTING" ]]; then
+ echo "PR #${PR_NUMBER} conflicts with its base branch, so GitHub has no merge result for it." >&2
+ return 1
+ fi
+ if (( $(date +%s) > deadline )); then
+ echo "GitHub has not computed PR #${PR_NUMBER}'s merge commit yet (mergeable=${mergeable})." >&2
+ return 1
+ fi
+ echo "Merge commit not computed yet (mergeable=${mergeable}); waiting." >&2
+ sleep 10
+ done
+ }
+ # ------------------------------------------------------------------------------
+ # --- merge result native check ------------------------------------------------
+ # merge_result_native_check <hash> <listing> <fetch>: is the native code of
+ # PR #PR_NUMBER's merge result the native code of the commit this run built
+ # or is about to build — BUILT_SHA when set (a job that checked out other
+ # code, such as main's, to judge it), else HEAD? The merge gate hashes the merge result, so a
+ # build that differs from it could never pass the gate. <hash> / <listing>
+ # print a commit's native hash / the listing behind it; <fetch> makes a
+ # commit available (the iOS and Android helpers differ). Needs GH_TOKEN,
+ # GH_REPO, PR_NUMBER, BASE_BRANCH, and pr_merge_commit.
+ #
+ # GitHub's test merge commit answers directly when it exists. It doesn't for
+ # a PR that conflicts with its base, but the question still has an answer:
+ # if the base's native code hasn't moved since the PR branched, merging can
+ # only carry HEAD's native code, whatever files the conflicts are in. A
+ # refusal lists the native files the base changed.
+ merge_result_native_check() {
+ local hash=$1 listing=$2 fetch=$3 built built_hash merge merge_hash compare tip \
+ merge_base tip_hash base_hash why files
+ # Callers run this under `if !`, which turns off `set -e` here, so every
+ # lookup is checked: an empty commit hashes the same on both sides and would
+ # pass an unchecked comparison.
+ built=${BUILT_SHA:-$(git rev-parse HEAD)}
+ if ! built_hash=$($hash "$built"); then
+ echo "Could not hash this build's native code (${built:0:10})." >&2
+ return 1
+ fi
+ merge=""
+ if merge=$(pr_merge_commit); then
+ if ! $fetch "$merge" || ! merge_hash=$($hash "$merge"); then
+ echo "Could not fetch or hash PR #${PR_NUMBER}'s merge result (${merge:0:10})." >&2
+ return 1
+ fi
+ if [[ "$merge_hash" == "$built_hash" ]]; then
+ echo "Native code matches the merge result ${merge:0:10}."
+ return 0
+ fi
+ why="PR #${PR_NUMBER}'s merge result (${merge:0:10}) has native code this build (${built:0:10}) lacks"
+ fi
+ if ! compare=$(gh api "repos/${GH_REPO}/compare/${BASE_BRANCH}...${built}" \
+ --jq '"\(.base_commit.sha) \(.merge_base_commit.sha)"'); then
+ echo "Could not compare ${BASE_BRANCH} with ${built:0:10}, so the merge result's native code is unverified." >&2
+ return 1
+ fi
+ read -r tip merge_base <<<"$compare"
+ if [[ -z "$tip" || -z "$merge_base" ]] || ! $fetch "$tip" || ! $fetch "$merge_base"; then
+ echo "Could not fetch ${BASE_BRANCH} (${tip:0:10}) or the PR's branch point (${merge_base:0:10})." >&2
+ return 1
+ fi
+ if [[ -z "$merge" ]]; then
+ if ! tip_hash=$($hash "$tip") || ! base_hash=$($hash "$merge_base"); then
+ echo "Could not hash ${BASE_BRANCH} (${tip:0:10}) or the PR's branch point (${merge_base:0:10})." >&2
+ return 1
+ fi
+ if [[ "$tip_hash" == "$base_hash" ]]; then
+ echo "PR #${PR_NUMBER} has no merge result (conflicts, or GitHub has not computed it), but ${BASE_BRANCH} (${tip:0:10})" \
+ "still has the native code the PR branched from (${merge_base:0:10}), so merging can only carry this build's native code."
+ return 0
+ fi
+ why="PR #${PR_NUMBER} has no merge result (conflicts, or GitHub has not computed it), and ${BASE_BRANCH} changed native code since the PR branched"
+ fi
+ # Listing lines are `<mode> <type> <sha>\t<path>` or `cache-wasm-version <v>`.
+ # awk splits on the tab portably; BSD sed has no `\t` in a bracket.
+ files=$({ diff <($listing "$merge_base") <($listing "$tip") || true; } \
+ | awk -F'\t' '/^[<>] cache-wasm-version / { print " " substr($0, 3); next }
+ /^[<>] / && NF > 1 { print " " $2 }' | sort -u)
+ echo "${why}. Native changes on ${BASE_BRANCH} since ${merge_base:0:10}" \
+ "(https://github.com/${GH_REPO}/compare/${merge_base:0:10}...${tip:0:10}):" >&2
+ echo "${files:- (none listed: an excluded path?)}" >&2
+ return 1
+ }
+ # ------------------------------------------------------------------------------
+ set -euo pipefail
+ # Last check before uploading (and before promoting): the bundle must still describe the native code
+ # the merge gate will hash — that of the PR's merge result — or it could never
+ # pass the gate, and a promoted Play release cannot be withdrawn. Two things
+ # can move while a build runs: the PR head (a native push; the drift workflow
+ # cancels runs after the fact, but better not to upload at all) and main
+ # (another Android PR merged). The build is HEAD, or BUILT_SHA when set (the
+ # publisher judges a PR build from main's checkout). GUARD_STAGE=promote words
+ # it for the check before the production promotion, after the upload to the
+ # internal track has used the version code up.
+ if [[ "${GUARD_STAGE:-upload}" == promote ]]; then
+ verb=promoting
+ done_msg="Promoting"
+ retry="Version code is used up on the internal track: bump (cd apps/web && just android-bump), commit, and re-add the android-update label."
+ else
+ verb=uploading
+ done_msg="Uploading"
+ retry="Re-add the android-update label to release the current head."
+ fi
+ built_sha=${BUILT_SHA:-$(git rev-parse HEAD)}
+ if [[ -n "${BUILT_SHA:-}" ]]; then
+ gh_fetch "$BUILT_SHA"
+ fi
+ built=$(bun scripts/android-native.mjs hash "$built_sha")
+ head_sha=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json headRefOid --jq '.headRefOid')
+ if [[ "$head_sha" == "$built_sha" ]]; then
+ echo "PR head unchanged (${head_sha:0:10}); native hash ${built:0:10} is current."
+ else
+ gh_fetch "$head_sha"
+ current=$(bun scripts/android-native.mjs hash "$head_sha")
+ if [[ "$current" != "$built" ]]; then
+ echo "Android native code changed on PR #${PR_NUMBER} while this release was building" \
+ "(${built:0:10} → ${current:0:10}). Not ${verb} the stale bundle." >&2
+ echo "$retry" >&2
+ exit 1
+ fi
+ echo "PR head moved to ${head_sha:0:10} but its Android native code is unchanged (${built:0:10})."
+ fi
+ if ! merge_result_native_check "bun scripts/android-native.mjs hash" "bun scripts/android-native.mjs listing" gh_fetch; then
+ echo "Android native code landed on ${BASE_BRANCH} while this release was building. Not ${verb} the bundle" \
+ "(native hash ${built:0:10}): the merge gate could never accept it." >&2
+ echo "Merge ${BASE_BRANCH} into the PR, bump (cd apps/web && just android-bump), commit, and re-add the android-update label." >&2
+ exit 1
+ fi
+ echo "${done_msg} the bundle (native hash ${built:0:10})."
+ shell: bash
+ env:
+ LOGGED_STEP: Require the PR's Android native code to be unchanged since the build
+ GUARD_STAGE: upload
+ working-directory: apps/web
+ - id: stamp
+ name: Write the provenance stamp as release notes
+ run: |
+ printf '%s\n' "$LOGGED_STEP" > "$RUNNER_TEMP/last-step.name"
+ exec > >(tee "$RUNNER_TEMP/last-step.log") 2>&1
+ set -euo pipefail
+ hash=$(bun scripts/android-native.mjs hash "$BUILT_SHA")
+ mkdir -p "$RUNNER_TEMP/whatsnew"
+ printf 'native tree %s for PR #%s\n' "$hash" "$PR_NUMBER" > "$RUNNER_TEMP/whatsnew/whatsnew-en-US"
+ echo "native_hash=${hash}" >> "$GITHUB_OUTPUT"
+ echo "Stamp: native tree ${hash} for PR #${PR_NUMBER}"
+ shell: bash
+ env:
+ LOGGED_STEP: Write the provenance stamp as release notes
+ working-directory: apps/web
+ - name: Download the built App Bundle
+ uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0
+ with:
+ name: android-release
+ run-id: ${{ github.event.workflow_run.id }}
+ github-token: ${{ github.token }}
+ path: ${{ runner.temp }}/android-release
+ - id: artifact
+ name: Pick the bundle and its R8 mapping
+ run: |
+ printf '%s\n' "$LOGGED_STEP" > "$RUNNER_TEMP/last-step.name"
+ exec > >(tee "$RUNNER_TEMP/last-step.log") 2>&1
+ set -euo pipefail
+ dir="$RUNNER_TEMP/android-release"
+ mapfile -t bundles < <(find "$dir" -maxdepth 1 -type f -name '*.aab' -printf '%f\n')
+ mapfile -t mappings < <(find "$dir" -maxdepth 1 -type f -name '*-mapping.txt' -printf '%f\n')
+ if (( ${#bundles[@]} != 1 || ${#mappings[@]} != 1 )); then
+ echo "Expected one .aab and one -mapping.txt in the android-release artifact, found ${#bundles[@]} and ${#mappings[@]}." >&2
+ exit 1
+ fi
+ for name in "${bundles[0]}" "${mappings[0]}"; do
+ if [[ ! "$name" =~ ^[A-Za-z0-9._-]+$ ]]; then
+ echo "Refusing the artifact file name ${name}." >&2
+ exit 1
+ fi
+ done
+ echo "bundle=${dir}/${bundles[0]}" >> "$GITHUB_OUTPUT"
+ echo "mapping=${dir}/${mappings[0]}" >> "$GITHUB_OUTPUT"
+ echo "Bundle ${bundles[0]}, mapping ${mappings[0]}."
+ shell: bash
+ env:
+ LOGGED_STEP: Pick the bundle and its R8 mapping
+ - id: auth
+ name: Authenticate to Google Play
+ uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093
+ with:
+ workload_identity_provider: ${{ vars.GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER }}
+ service_account: ${{ vars.GOOGLE_PLAY_SERVICE_ACCOUNT }}
+ token_format: access_token
+ access_token_scopes: https://www.googleapis.com/auth/androidpublisher
+ export_environment_variables: 'false'
+ - id: upload
+ name: Upload to internal testing
+ uses: r0adkll/upload-google-play@e738b9dd8f2476ea806d921b64aacd24f34515a5
+ with:
+ serviceAccountJson: ${{ steps.auth.outputs.credentials_file_path }}
+ packageName: com.macro.workspace.mobile
+ releaseFiles: ${{ steps.artifact.outputs.bundle }}
+ mappingFile: ${{ steps.artifact.outputs.mapping }}
+ releaseName: ${{ needs.check.outputs.release_name }}
+ track: internal
+ status: completed
+ whatsNewDirectory: ${{ runner.temp }}/whatsnew
+ - name: Require the native code to be unchanged before promoting
+ run: |
+ printf '%s\n' "$LOGGED_STEP" > "$RUNNER_TEMP/last-step.name"
+ exec > >(tee "$RUNNER_TEMP/last-step.log") 2>&1
+ # --- authenticated fetch ------------------------------------------------------
+ # gh_fetch <sha|ref>: make a commit that is not in this checkout (the base
+ # commit, a moved PR head, GitHub's test merge commit) available. Checkouts
+ # may persist credentials, so clear inherited headers before supplying one
+ # explicitly. Keep Nix build libraries out of the host Git HTTPS helper.
+ # Fails if the commit is unreachable (a force-pushed-away head).
+ gh_fetch() {
+ local auth
+ auth=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 | tr -d '\n')
+ LD_LIBRARY_PATH= git -c "http.https://github.com/.extraheader=" \
+ -c "http.https://github.com/.extraheader=AUTHORIZATION: basic ${auth}" \
+ fetch -q --depth=1 origin "$1"
+ }
+ # ------------------------------------------------------------------------------
+ # --- PR merge result ----------------------------------------------------------
+ # pr_merge_commit: print the sha of GitHub's test merge commit for $PR_NUMBER —
+ # the merge result the native gates hash. GitHub computes it lazily
+ # (mergeable=UNKNOWN until it has), so poll a little; a PR that really
+ # conflicts with its base cannot merge anyway. Needs GH_TOKEN, GH_REPO,
+ # PR_NUMBER. Progress goes to stderr so `merge=$(pr_merge_commit)` works.
+ pr_merge_commit() {
+ local deadline pr_json mergeable merge
+ deadline=$(( $(date +%s) + 120 ))
+ while true; do
+ pr_json=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json mergeable,potentialMergeCommit)
+ mergeable=$(jq -r '.mergeable' <<<"$pr_json")
+ merge=$(jq -r '.potentialMergeCommit.oid // empty' <<<"$pr_json")
+ if [[ -n "$merge" ]]; then
+ echo "$merge"
+ return 0
+ fi
+ if [[ "$mergeable" == "CONFLICTING" ]]; then
+ echo "PR #${PR_NUMBER} conflicts with its base branch, so GitHub has no merge result for it." >&2
+ return 1
+ fi
+ if (( $(date +%s) > deadline )); then
+ echo "GitHub has not computed PR #${PR_NUMBER}'s merge commit yet (mergeable=${mergeable})." >&2
+ return 1
+ fi
+ echo "Merge commit not computed yet (mergeable=${mergeable}); waiting." >&2
+ sleep 10
+ done
+ }
+ # ------------------------------------------------------------------------------
+ # --- merge result native check ------------------------------------------------
+ # merge_result_native_check <hash> <listing> <fetch>: is the native code of
+ # PR #PR_NUMBER's merge result the native code of the commit this run built
+ # or is about to build — BUILT_SHA when set (a job that checked out other
+ # code, such as main's, to judge it), else HEAD? The merge gate hashes the merge result, so a
+ # build that differs from it could never pass the gate. <hash> / <listing>
+ # print a commit's native hash / the listing behind it; <fetch> makes a
+ # commit available (the iOS and Android helpers differ). Needs GH_TOKEN,
+ # GH_REPO, PR_NUMBER, BASE_BRANCH, and pr_merge_commit.
+ #
+ # GitHub's test merge commit answers directly when it exists. It doesn't for
+ # a PR that conflicts with its base, but the question still has an answer:
+ # if the base's native code hasn't moved since the PR branched, merging can
+ # only carry HEAD's native code, whatever files the conflicts are in. A
+ # refusal lists the native files the base changed.
+ merge_result_native_check() {
+ local hash=$1 listing=$2 fetch=$3 built built_hash merge merge_hash compare tip \
+ merge_base tip_hash base_hash why files
+ # Callers run this under `if !`, which turns off `set -e` here, so every
+ # lookup is checked: an empty commit hashes the same on both sides and would
+ # pass an unchecked comparison.
+ built=${BUILT_SHA:-$(git rev-parse HEAD)}
+ if ! built_hash=$($hash "$built"); then
+ echo "Could not hash this build's native code (${built:0:10})." >&2
+ return 1
+ fi
+ merge=""
+ if merge=$(pr_merge_commit); then
+ if ! $fetch "$merge" || ! merge_hash=$($hash "$merge"); then
+ echo "Could not fetch or hash PR #${PR_NUMBER}'s merge result (${merge:0:10})." >&2
+ return 1
+ fi
+ if [[ "$merge_hash" == "$built_hash" ]]; then
+ echo "Native code matches the merge result ${merge:0:10}."
+ return 0
+ fi
+ why="PR #${PR_NUMBER}'s merge result (${merge:0:10}) has native code this build (${built:0:10}) lacks"
+ fi
+ if ! compare=$(gh api "repos/${GH_REPO}/compare/${BASE_BRANCH}...${built}" \
+ --jq '"\(.base_commit.sha) \(.merge_base_commit.sha)"'); then
+ echo "Could not compare ${BASE_BRANCH} with ${built:0:10}, so the merge result's native code is unverified." >&2
+ return 1
+ fi
+ read -r tip merge_base <<<"$compare"
+ if [[ -z "$tip" || -z "$merge_base" ]] || ! $fetch "$tip" || ! $fetch "$merge_base"; then
+ echo "Could not fetch ${BASE_BRANCH} (${tip:0:10}) or the PR's branch point (${merge_base:0:10})." >&2
+ return 1
+ fi
+ if [[ -z "$merge" ]]; then
+ if ! tip_hash=$($hash "$tip") || ! base_hash=$($hash "$merge_base"); then
+ echo "Could not hash ${BASE_BRANCH} (${tip:0:10}) or the PR's branch point (${merge_base:0:10})." >&2
+ return 1
+ fi
+ if [[ "$tip_hash" == "$base_hash" ]]; then
+ echo "PR #${PR_NUMBER} has no merge result (conflicts, or GitHub has not computed it), but ${BASE_BRANCH} (${tip:0:10})" \
+ "still has the native code the PR branched from (${merge_base:0:10}), so merging can only carry this build's native code."
+ return 0
+ fi
+ why="PR #${PR_NUMBER} has no merge result (conflicts, or GitHub has not computed it), and ${BASE_BRANCH} changed native code since the PR branched"
+ fi
+ # Listing lines are `<mode> <type> <sha>\t<path>` or `cache-wasm-version <v>`.
+ # awk splits on the tab portably; BSD sed has no `\t` in a bracket.
+ files=$({ diff <($listing "$merge_base") <($listing "$tip") || true; } \
+ | awk -F'\t' '/^[<>] cache-wasm-version / { print " " substr($0, 3); next }
+ /^[<>] / && NF > 1 { print " " $2 }' | sort -u)
+ echo "${why}. Native changes on ${BASE_BRANCH} since ${merge_base:0:10}" \
+ "(https://github.com/${GH_REPO}/compare/${merge_base:0:10}...${tip:0:10}):" >&2
+ echo "${files:- (none listed: an excluded path?)}" >&2
+ return 1
+ }
+ # ------------------------------------------------------------------------------
+ set -euo pipefail
+ # Last check before uploading (and before promoting): the bundle must still describe the native code
+ # the merge gate will hash — that of the PR's merge result — or it could never
+ # pass the gate, and a promoted Play release cannot be withdrawn. Two things
+ # can move while a build runs: the PR head (a native push; the drift workflow
+ # cancels runs after the fact, but better not to upload at all) and main
+ # (another Android PR merged). The build is HEAD, or BUILT_SHA when set (the
+ # publisher judges a PR build from main's checkout). GUARD_STAGE=promote words
+ # it for the check before the production promotion, after the upload to the
+ # internal track has used the version code up.
+ if [[ "${GUARD_STAGE:-upload}" == promote ]]; then
+ verb=promoting
+ done_msg="Promoting"
+ retry="Version code is used up on the internal track: bump (cd apps/web && just android-bump), commit, and re-add the android-update label."
+ else
+ verb=uploading
+ done_msg="Uploading"
+ retry="Re-add the android-update label to release the current head."
+ fi
+ built_sha=${BUILT_SHA:-$(git rev-parse HEAD)}
+ if [[ -n "${BUILT_SHA:-}" ]]; then
+ gh_fetch "$BUILT_SHA"
+ fi
+ built=$(bun scripts/android-native.mjs hash "$built_sha")
+ head_sha=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json headRefOid --jq '.headRefOid')
+ if [[ "$head_sha" == "$built_sha" ]]; then
+ echo "PR head unchanged (${head_sha:0:10}); native hash ${built:0:10} is current."
+ else
+ gh_fetch "$head_sha"
+ current=$(bun scripts/android-native.mjs hash "$head_sha")
+ if [[ "$current" != "$built" ]]; then
+ echo "Android native code changed on PR #${PR_NUMBER} while this release was building" \
+ "(${built:0:10} → ${current:0:10}). Not ${verb} the stale bundle." >&2
+ echo "$retry" >&2
+ exit 1
+ fi
+ echo "PR head moved to ${head_sha:0:10} but its Android native code is unchanged (${built:0:10})."
+ fi
+ if ! merge_result_native_check "bun scripts/android-native.mjs hash" "bun scripts/android-native.mjs listing" gh_fetch; then
+ echo "Android native code landed on ${BASE_BRANCH} while this release was building. Not ${verb} the bundle" \
+ "(native hash ${built:0:10}): the merge gate could never accept it." >&2
+ echo "Merge ${BASE_BRANCH} into the PR, bump (cd apps/web && just android-bump), commit, and re-add the android-update label." >&2
+ exit 1
+ fi
+ echo "${done_msg} the bundle (native hash ${built:0:10})."
+ shell: bash
+ env:
+ LOGGED_STEP: Require the native code to be unchanged before promoting
+ GUARD_STAGE: promote
+ working-directory: apps/web
+ - id: pending
+ name: Mark the promotion as started
+ run: |
+ # --- Android Play commit statuses ---------------------------------------------
+ # Only workflows that run main's copy may sign in to Google Play, so they
+ # record what they learn as commit statuses on the PR's commits, where the
+ # PR-side jobs (the merge gate, the drift check) read it:
+ #
+ # android-play/release set by Android Play Publish on the commit it built:
+ # pending just before the production promotion, then
+ # success or failure.
+ # android-play/live set by Android Release Watch on the PR head once the
+ # release is live on production.
+ #
+ # Readers match the descriptions exactly, so they are built only here.
+ # Needs GH_TOKEN and GH_REPO; pr_commit_statuses also PR_NUMBER.
+
+ # android_release_description <version code> <native hash>
+ android_release_description() {
+ printf 'Version code %s (native tree %s)' "$1" "$2"
+ }
+
+ # android_live_description <version code> <native hash> <PR number>
+ android_live_description() {
+ printf 'Version code %s is live on Google Play (native tree %s, PR #%s)' "$1" "$2" "$3"
+ }
+
+ # commit_status <sha> <context>: `<state> <description>` of the commit's latest
+ # status with that context, or nothing.
+ commit_status() {
+ gh api "repos/${GH_REPO}/commits/$1/status" \
+ --jq ".statuses[] | select(.context == \"$2\") | \"\(.state) \(.description)\""
+ }
+
+ # pr_commit_statuses <context>: `<sha> <state> <description>` for each of PR
+ # #PR_NUMBER's last 100 commits that has a status with that context (its
+ # latest one), states in lower case like the REST API's.
+ pr_commit_statuses() {
+ gh api graphql -F owner="${GH_REPO%%/*}" -F name="${GH_REPO#*/}" -F pr="$PR_NUMBER" -F context="$1" \
+ -f query='query($owner: String!, $name: String!, $pr: Int!, $context: String!) {
+ repository(owner: $owner, name: $name) {
+ pullRequest(number: $pr) {
+ commits(last: 100) { nodes { commit { oid status { context(name: $context) { state description } } } } }
+ }
+ }
+ }' \
+ --jq '.data.repository.pullRequest.commits.nodes[].commit
+ | select(.status.context != null)
+ | "\(.oid) \(.status.context.state | ascii_downcase) \(.status.context.description)"'
+ }
+
+ # set_commit_status <sha> <context> <state> <description>, linking this run.
+ set_commit_status() {
+ gh api "repos/${GH_REPO}/statuses/$1" -f context="$2" -f state="$3" -f description="$4" \
+ -f target_url="${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" >/dev/null
+ }
+ # ------------------------------------------------------------------------------
+ set -euo pipefail
+ set_commit_status "$BUILT_SHA" android-play/release pending \
+ "$(android_release_description "$VERSION_CODE" "$NATIVE_HASH")"
+ shell: bash
+ env:
+ NATIVE_HASH: ${{ steps.stamp.outputs.native_hash }}
+ - id: promote
+ name: Promote to production
+ run: |
+ printf '%s\n' "$LOGGED_STEP" > "$RUNNER_TEMP/last-step.name"
+ exec > >(tee "$RUNNER_TEMP/last-step.log") 2>&1
+ set -euo pipefail
+ for attempt in 1 2 3 4 5; do
+ if node scripts/android-play-promote.mjs; then
+ exit 0
+ fi
+ echo "Promotion attempt ${attempt} failed; retrying in 30s."
+ sleep 30
+ done
+ echo "Could not promote version code ${VERSION_CODE} to production; promote it by hand with publish-android-play.yml (operation=promote-production)." >&2
+ exit 1
+ shell: bash
+ env:
+ LOGGED_STEP: Promote to production
+ GOOGLE_PLAY_ACCESS_TOKEN: ${{ steps.auth.outputs.access_token }}
+ CHANGES_NOT_SENT_FOR_REVIEW: 'false'
+ working-directory: apps/web
+ - name: Record the promotion result
+ if: always() && steps.pending.outcome == 'success'
+ run: |
+ # --- Android Play commit statuses ---------------------------------------------
+ # Only workflows that run main's copy may sign in to Google Play, so they
+ # record what they learn as commit statuses on the PR's commits, where the
+ # PR-side jobs (the merge gate, the drift check) read it:
+ #
+ # android-play/release set by Android Play Publish on the commit it built:
+ # pending just before the production promotion, then
+ # success or failure.
+ # android-play/live set by Android Release Watch on the PR head once the
+ # release is live on production.
+ #
+ # Readers match the descriptions exactly, so they are built only here.
+ # Needs GH_TOKEN and GH_REPO; pr_commit_statuses also PR_NUMBER.
+
+ # android_release_description <version code> <native hash>
+ android_release_description() {
+ printf 'Version code %s (native tree %s)' "$1" "$2"
+ }
+
+ # android_live_description <version code> <native hash> <PR number>
+ android_live_description() {
+ printf 'Version code %s is live on Google Play (native tree %s, PR #%s)' "$1" "$2" "$3"
+ }
+
+ # commit_status <sha> <context>: `<state> <description>` of the commit's latest
+ # status with that context, or nothing.
+ commit_status() {
+ gh api "repos/${GH_REPO}/commits/$1/status" \
+ --jq ".statuses[] | select(.context == \"$2\") | \"\(.state) \(.description)\""
+ }
+
+ # pr_commit_statuses <context>: `<sha> <state> <description>` for each of PR
+ # #PR_NUMBER's last 100 commits that has a status with that context (its
+ # latest one), states in lower case like the REST API's.
+ pr_commit_statuses() {
+ gh api graphql -F owner="${GH_REPO%%/*}" -F name="${GH_REPO#*/}" -F pr="$PR_NUMBER" -F context="$1" \
+ -f query='query($owner: String!, $name: String!, $pr: Int!, $context: String!) {
+ repository(owner: $owner, name: $name) {
+ pullRequest(number: $pr) {
+ commits(last: 100) { nodes { commit { oid status { context(name: $context) { state description } } } } }
+ }
+ }
+ }' \
+ --jq '.data.repository.pullRequest.commits.nodes[].commit
+ | select(.status.context != null)
+ | "\(.oid) \(.status.context.state | ascii_downcase) \(.status.context.description)"'
+ }
+
+ # set_commit_status <sha> <context> <state> <description>, linking this run.
+ set_commit_status() {
+ gh api "repos/${GH_REPO}/statuses/$1" -f context="$2" -f state="$3" -f description="$4" \
+ -f target_url="${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" >/dev/null
+ }
+ # ------------------------------------------------------------------------------
+ set -euo pipefail
+ state=failure
+ if [[ "$PROMOTE_OUTCOME" == success ]]; then
+ state=success
+ fi
+ set_commit_status "$BUILT_SHA" android-play/release "$state" \
+ "$(android_release_description "$VERSION_CODE" "$NATIVE_HASH")"
+ shell: bash
+ env:
+ NATIVE_HASH: ${{ steps.stamp.outputs.native_hash }}
+ PROMOTE_OUTCOME: ${{ steps.promote.outcome }}
+ - name: Comment on the PR
+ if: success() || failure()
+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b
+ with:
+ github-token: ${{ secrets.GITHUB_TOKEN }}
+ script: |
+ // Android Play Publish's closing comment on the PR (actions/github-script).
+ // A failure names the step that failed and, when it is one that logs its
+ // output (steps::logged_run), quotes the end of that output.
+ const fs = require('fs');
+ const path = require('path');
+ const env = process.env;
+ const versionCode = env.VERSION_CODE || '?';
+ const releaseName = env.RELEASE_NAME || `version code ${versionCode}`;
+ const runUrl =
+ `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}` +
+ `/actions/runs/${context.runId}`;
+ const runs = `[build](${env.BUILD_URL}), [publish](${runUrl})`;
+ let body;
+ if (env.JOB_STATUS === 'success') {
+ body = [
+ `🤖 Android ${releaseName} was uploaded to Google Play internal testing and submitted for a full production rollout (${runs}).`,
+ '',
+ 'When Google approves it, the version goes live, the **Android Release Watch** workflow',
+ 'marks this PR `android-play/live` and re-runs the **Android Native Check** within half an hour',
+ 'of that, and the PR becomes mergeable. To merge it the moment that happens, click',
+ '**Enable auto-merge** on this PR now (squash).',
+ 'After merge, the next prod deploy applies the Android native build floor committed in `min-native-build.json`.',
+ ].join('\n');
+ } else {
+ let failedStep = null;
+ try {
+ const { data } = await github.rest.actions.listJobsForWorkflowRunAttempt({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ run_id: context.runId,
+ attempt_number: Number(env.GITHUB_RUN_ATTEMPT),
+ });
+ const job = data.jobs.find((j) => j.name === env.JOB_NAME);
+ failedStep = job?.steps.find((s) => s.conclusion === 'failure')?.name ?? null;
+ } catch (error) {
+ core.warning(`Could not list this job's steps: ${error.message}`);
+ }
+ const read = (file) => {
+ try {
+ return fs.readFileSync(path.join(env.RUNNER_TEMP, file), 'utf8');
+ } catch {
+ return '';
+ }
+ };
+ let tail = '';
+ if (failedStep && read('last-step.name').trim() === failedStep) {
+ const lines = read('last-step.log').replace(/\x1b\[[0-9;]*m/g, '').trimEnd().split('\n');
+ tail = lines.slice(-30).join('\n').slice(-3000);
+ }
+ const retry =
+ env.UPLOAD_OUTCOME === 'success'
+ ? [
+ `The bundle reached the internal track, so version code ${versionCode} is used up: bump`,
+ '(`cd apps/web && just android-bump`), commit, and re-add the `android-update` label.',
+ 'If only the promotion failed and the native code is unchanged, you can instead promote',
+ `version code ${versionCode} by hand with **Publish Android to Google Play** (\`operation=promote-production\`).`,
+ ].join('\n')
+ : 'Fix the problem, then remove and re-add the `android-update` label to retry.';
+ body = [
+ `🤖 Android Play release for ${releaseName} **failed**${failedStep ? ` at **${failedStep}**` : ''} (${runs}).`,
+ ...(tail ? ['', '```text', tail, '```'] : []),
+ '',
+ retry,
+ ].join('\n');
+ }
+ await github.rest.issues.createComment({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: Number(env.PR_NUMBER),
+ body,
+ });
+ env:
+ JOB_NAME: Android Play Publish
+ BUILD_URL: ${{ github.event.workflow_run.html_url }}
+ RELEASE_NAME: ${{ needs.check.outputs.release_name }}
+ JOB_STATUS: ${{ job.status }}
+ UPLOAD_OUTCOME: ${{ steps.upload.outcome }}
diff --git a/.github/workflows/android-play-release.yml b/.github/workflows/android-play-release.yml
index c806cf8989..4db7b475b2 100644
--- a/.github/workflows/android-play-release.yml
+++ b/.github/workflows/android-play-release.yml
@@ -16,7 +16,6 @@ jobs:
pull-requests: write
checks: read
statuses: read
- id-token: write
env:
CI: 'true'
GH_TOKEN: ${{ github.token }}
@@ -85,8 +84,9 @@ jobs:
# ------------------------------------------------------------------------------
# --- merge result native check ------------------------------------------------
# merge_result_native_check <hash> <listing> <fetch>: is the native code of
- # PR #PR_NUMBER's merge result the native code of HEAD, the code this run
- # built or is about to build? The merge gate hashes the merge result, so a
+ # PR #PR_NUMBER's merge result the native code of the commit this run built
+ # or is about to build — BUILT_SHA when set (a job that checked out other
+ # code, such as main's, to judge it), else HEAD? The merge gate hashes the merge result, so a
# build that differs from it could never pass the gate. <hash> / <listing>
# print a commit's native hash / the listing behind it; <fetch> makes a
# commit available (the iOS and Android helpers differ). Needs GH_TOKEN,
@@ -103,7 +103,7 @@ jobs:
# Callers run this under `if !`, which turns off `set -e` here, so every
# lookup is checked: an empty commit hashes the same on both sides and would
# pass an unchecked comparison.
- built=$(git rev-parse HEAD)
+ built=${BUILT_SHA:-$(git rev-parse HEAD)}
if ! built_hash=$($hash "$built"); then
echo "Could not hash this build's native code (${built:0:10})." >&2
return 1
@@ -202,8 +202,10 @@ jobs:
echo "version_code=${version_code}" >> "$GITHUB_OUTPUT"
echo "Releasing Android version code ${version_code}."
- # (`gh pr checks` names are job names, not workflow names.)
- ours='^(Android Native Check|Android Play Release|Re-run the native check|Web App Status Check|Android Release Drift|iOS Native Check)'
+ # (`gh pr checks` names are job names, not workflow names, plus the contexts
+ # of commit statuses, such as the android-play/* ones Android Play Publish
+ # and Android Release Watch set.)
+ ours='^(Android Native Check|Android Play Release|Re-run the native check|Web App Status Check|Android Release Drift|iOS Native Check|android-play/)'
deadline=$(( $(date +%s) + WAIT_MINUTES * 60 ))
while true; do
checks=$(gh pr checks "$PR_NUMBER" --repo "$GH_REPO" --json name,bucket \
@@ -384,8 +386,9 @@ jobs:
# ------------------------------------------------------------------------------
# --- merge result native check ------------------------------------------------
# merge_result_native_check <hash> <listing> <fetch>: is the native code of
- # PR #PR_NUMBER's merge result the native code of HEAD, the code this run
- # built or is about to build? The merge gate hashes the merge result, so a
+ # PR #PR_NUMBER's merge result the native code of the commit this run built
+ # or is about to build — BUILT_SHA when set (a job that checked out other
+ # code, such as main's, to judge it), else HEAD? The merge gate hashes the merge result, so a
# build that differs from it could never pass the gate. <hash> / <listing>
# print a commit's native hash / the listing behind it; <fetch> makes a
# commit available (the iOS and Android helpers differ). Needs GH_TOKEN,
@@ -402,7 +405,7 @@ jobs:
# Callers run this under `if !`, which turns off `set -e` here, so every
# lookup is checked: an empty commit hashes the same on both sides and would
# pass an unchecked comparison.
- built=$(git rev-parse HEAD)
+ built=${BUILT_SHA:-$(git rev-parse HEAD)}
if ! built_hash=$($hash "$built"); then
echo "Could not hash this build's native code (${built:0:10})." >&2
return 1
@@ -453,51 +456,54 @@ jobs:
}
# ------------------------------------------------------------------------------
set -euo pipefail
- # Last check before uploading: the bundle must still describe the native code
+ # Last check before uploading (and before promoting): the bundle must still describe the native code
# the merge gate will hash — that of the PR's merge result — or it could never
# pass the gate, and a promoted Play release cannot be withdrawn. Two things
# can move while a build runs: the PR head (a native push; the drift workflow
# cancels runs after the fact, but better not to upload at all) and main
- # (another Android PR merged).
- built=$(bun scripts/android-native.mjs hash HEAD)
+ # (another Android PR merged). The build is HEAD, or BUILT_SHA when set (the
+ # publisher judges a PR build from main's checkout). GUARD_STAGE=promote words
+ # it for the check before the production promotion, after the upload to the
+ # internal track has used the version code up.
+ if [[ "${GUARD_STAGE:-upload}" == promote ]]; then
+ verb=promoting
+ done_msg="Promoting"
+ retry="Version code is used up on the internal track: bump (cd apps/web && just android-bump), commit, and re-add the android-update label."
+ else
+ verb=uploading
+ done_msg="Uploading"
+ retry="Re-add the android-update label to release the current head."
+ fi
+ built_sha=${BUILT_SHA:-$(git rev-parse HEAD)}
+ if [[ -n "${BUILT_SHA:-}" ]]; then
+ gh_fetch "$BUILT_SHA"
+ fi
+ built=$(bun scripts/android-native.mjs hash "$built_sha")
head_sha=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json headRefOid --jq '.headRefOid')
- if [[ "$head_sha" == "$(git rev-parse HEAD)" ]]; then
+ if [[ "$head_sha" == "$built_sha" ]]; then
echo "PR head unchanged (${head_sha:0:10}); native hash ${built:0:10} is current."
else
gh_fetch "$head_sha"
current=$(bun scripts/android-native.mjs hash "$head_sha")
if [[ "$current" != "$built" ]]; then
echo "Android native code changed on PR #${PR_NUMBER} while this release was building" \
- "(${built:0:10} → ${current:0:10}). Not uploading the stale bundle." >&2
- echo "Re-add the android-update label to release the current head." >&2
+ "(${built:0:10} → ${current:0:10}). Not ${verb} the stale bundle." >&2
+ echo "$retry" >&2
exit 1
fi
echo "PR head moved to ${head_sha:0:10} but its Android native code is unchanged (${built:0:10})."
fi
if ! merge_result_native_check "bun scripts/android-native.mjs hash" "bun scripts/android-native.mjs listing" gh_fetch; then
- echo "Android native code landed on ${BASE_BRANCH} while this release was building. Not uploading the bundle" \
+ echo "Android native code landed on ${BASE_BRANCH} while this release was building. Not ${verb} the bundle" \
"(native hash ${built:0:10}): the merge gate could never accept it." >&2
echo "Merge ${BASE_BRANCH} into the PR, bump (cd apps/web && just android-bump), commit, and re-add the android-update label." >&2
exit 1
fi
- echo "Uploading the bundle (native hash ${built:0:10})."
+ echo "${done_msg} the bundle (native hash ${built:0:10})."
shell: bash
env:
LOGGED_STEP: Require the PR's Android native code to be unchanged since the build
working-directory: apps/web
- - name: Write the provenance stamp as release notes
- run: |
- printf '%s\n' "$LOGGED_STEP" > "$RUNNER_TEMP/last-step.name"
- exec > >(tee "$RUNNER_TEMP/last-step.log") 2>&1
- set -euo pipefail
- hash=$(bun scripts/android-native.mjs hash HEAD)
- mkdir -p "$RUNNER_TEMP/whatsnew"
- printf 'native tree %s for PR #%s\n' "$hash" "$PR_NUMBER" > "$RUNNER_TEMP/whatsnew/whatsnew-en-US"
- echo "Stamp: native tree ${hash} for PR #${PR_NUMBER}"
- shell: bash
- env:
- LOGGED_STEP: Write the provenance stamp as release notes
- working-directory: apps/web
- name: Upload verified Android artifact
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
with:
@@ -505,56 +511,15 @@ jobs:
path: android-artifacts/
if-no-files-found: error
retention-days: '90'
- - id: auth
- name: Authenticate to Google Play
- uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093
- with:
- workload_identity_provider: ${{ vars.GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER }}
- service_account: ${{ vars.GOOGLE_PLAY_SERVICE_ACCOUNT }}
- token_format: access_token
- access_token_scopes: https://www.googleapis.com/auth/androidpublisher
- export_environment_variables: 'false'
- - name: Upload to internal testing
- uses: r0adkll/upload-google-play@e738b9dd8f2476ea806d921b64aacd24f34515a5
- with:
- serviceAccountJson: ${{ steps.auth.outputs.credentials_file_path }}
- packageName: com.macro.workspace.mobile
- releaseFiles: ${{ steps.artifact.outputs.bundle }}
- mappingFile: ${{ steps.artifact.outputs.mapping }}
- releaseName: ${{ steps.metadata.outputs.release_name }}
- track: internal
- status: completed
- whatsNewDirectory: ${{ runner.temp }}/whatsnew
- - name: Promote to production
- run: |
- printf '%s\n' "$LOGGED_STEP" > "$RUNNER_TEMP/last-step.name"
- exec > >(tee "$RUNNER_TEMP/last-step.log") 2>&1
- set -euo pipefail
- for attempt in 1 2 3 4 5; do
- if node scripts/android-play-promote.mjs; then
- exit 0
- fi
- echo "Promotion attempt ${attempt} failed; retrying in 30s."
- sleep 30
- done
- echo "Could not promote version code ${VERSION_CODE} to production; promote it by hand with publish-android-play.yml (operation=promote-production)." >&2
- exit 1
- shell: bash
- env:
- LOGGED_STEP: Promote to production
- GOOGLE_PLAY_ACCESS_TOKEN: ${{ steps.auth.outputs.access_token }}
- VERSION_CODE: ${{ steps.preconditions.outputs.version_code }}
- CHANGES_NOT_SENT_FOR_REVIEW: 'false'
- working-directory: apps/web
- name: Remove signing material
if: always()
run: |
rm -rf "$RUNNER_TEMP/android-signing" "$RUNNER_TEMP/android-release.json" \
- "$RUNNER_TEMP/android-google-services.json" "$RUNNER_TEMP/whatsnew" || true
+ "$RUNNER_TEMP/android-google-services.json" || true
rm -f apps/web/tauri/src-tauri/gen/android/keystore.properties || true
shell: bash
- name: Comment on the PR
- if: success() || failure()
+ if: failure()
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
@@ -566,55 +531,39 @@ jobs:
const runUrl =
`${context.serverUrl}/${context.repo.owner}/${context.repo.repo}` +
`/actions/runs/${context.runId}`;
- const success = '${{ job.status }}' === 'success';
- const SUCCESS_BODY = [
- `🤖 Android ${releaseName} was uploaded to Google Play internal testing and submitted for a full production rollout.`,
- '',
- 'When Google approves it, the version goes live, the **Android Release Watch** workflow',
- 're-runs the **Android Native Check** on this PR within half an hour of that, and the PR',
- 'becomes mergeable. To merge it the moment that happens, click **Enable auto-merge** on this PR now (squash).',
- 'After merge, the next prod deploy applies the Android native build floor committed in `min-native-build.json`.',
- '',
- `[Workflow run](${runUrl})`,
- ].join('\n');
- let body;
- if (success) {
- body = SUCCESS_BODY;
- } else {
- // Name the failed step and, when it is one that logs its
- // output (steps::logged_run), quote the end of that output.
- let failedStep = null;
+ // Name the failed step and, when it is one that logs its
+ // output (steps::logged_run), quote the end of that output.
+ let failedStep = null;
+ try {
+ const { data } = await github.rest.actions.listJobsForWorkflowRunAttempt({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ run_id: context.runId,
+ attempt_number: Number(process.env.GITHUB_RUN_ATTEMPT),
+ });
+ const job = data.jobs.find((j) => j.name === 'Android Play Release');
+ failedStep = job?.steps.find((s) => s.conclusion === 'failure')?.name ?? null;
+ } catch (error) {
+ core.warning(`Could not list this job's steps: ${error.message}`);
+ }
+ const read = (file) => {
try {
- const { data } = await github.rest.actions.listJobsForWorkflowRunAttempt({
- owner: context.repo.owner,
- repo: context.repo.repo,
- run_id: context.runId,
- attempt_number: Number(process.env.GITHUB_RUN_ATTEMPT),
- });
- const job = data.jobs.find((j) => j.name === 'Android Play Release');
- failedStep = job?.steps.find((s) => s.conclusion === 'failure')?.name ?? null;
- } catch (error) {
- core.warning(`Could not list this job's steps: ${error.message}`);
+ return fs.readFileSync(path.join(process.env.RUNNER_TEMP, file), 'utf8');
+ } catch {
+ return '';
}
- const read = (file) => {
- try {
- return fs.readFileSync(path.join(process.env.RUNNER_TEMP, file), 'utf8');
- } catch {
- return '';
- }
- };
- let tail = '';
- if (failedStep && read('last-step.name').trim() === failedStep) {
- const lines = read('last-step.log').replace(/\x1b\[[0-9;]*m/g, '').trimEnd().split('\n');
- tail = lines.slice(-30).join('\n').slice(-3000);
- }
- body = [
- `🤖 Android Play release for ${releaseName} **failed**${failedStep ? ` at **${failedStep}**` : ''} — see the [workflow run](${runUrl}).`,
- ...(tail ? ['', '```text', tail, '```'] : []),
- '',
- 'Fix the problem, then remove and re-add the `android-update` label to retry.',
- ].join('\n');
+ };
+ let tail = '';
+ if (failedStep && read('last-step.name').trim() === failedStep) {
+ const lines = read('last-step.log').replace(/\x1b\[[0-9;]*m/g, '').trimEnd().split('\n');
+ tail = lines.slice(-30).join('\n').slice(-3000);
}
+ const body = [
+ `🤖 Android Play release for ${releaseName} **failed**${failedStep ? ` at **${failedStep}**` : ''} — see the [workflow run](${runUrl}).`,
+ ...(tail ? ['', '```text', tail, '```'] : []),
+ '',
+ 'Fix the problem, then remove and re-add the `android-update` label to retry.',
+ ].join('\n');
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
diff --git a/.github/workflows/android-release-drift.yml b/.github/workflows/android-release-drift.yml
index 12c93834a8..0f68d06899 100644
--- a/.github/workflows/android-release-drift.yml
+++ b/.github/workflows/android-release-drift.yml
@@ -14,12 +14,12 @@ jobs:
actions: write
contents: read
pull-requests: write
- id-token: write
+ statuses: read
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PR_NUMBER: ${{ github.event.pull_request.number }}
- timeout-minutes: 15
+ timeout-minutes: 20
steps:
- name: Checkout
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd
@@ -106,28 +106,114 @@ jobs:
shell: bash
env:
HEAD_REF: ${{ github.event.pull_request.head.ref }}
- - id: auth
- name: Authenticate to Google Play
- if: steps.detect.outputs.changed == 'true' && steps.detect.outputs.version_code != ''
- uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093
- with:
- workload_identity_provider: ${{ vars.GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER }}
- service_account: ${{ vars.GOOGLE_PLAY_SERVICE_ACCOUNT }}
- token_format: access_token
- access_token_scopes: https://www.googleapis.com/auth/androidpublisher
- create_credentials_file: 'false'
- export_environment_variables: 'false'
- id: status
- name: Check whether the stale version code is already on Play
+ name: Check whether the stale version code was submitted to production
if: steps.detect.outputs.changed == 'true' && steps.detect.outputs.version_code != ''
run: |
+ # --- Android Play commit statuses ---------------------------------------------
+ # Only workflows that run main's copy may sign in to Google Play, so they
+ # record what they learn as commit statuses on the PR's commits, where the
+ # PR-side jobs (the merge gate, the drift check) read it:
+ #
+ # android-play/release set by Android Play Publish on the commit it built:
+ # pending just before the production promotion, then
+ # success or failure.
+ # android-play/live set by Android Release Watch on the PR head once the
+ # release is live on production.
+ #
+ # Readers match the descriptions exactly, so they are built only here.
+ # Needs GH_TOKEN and GH_REPO; pr_commit_statuses also PR_NUMBER.
+
+ # android_release_description <version code> <native hash>
+ android_release_description() {
+ printf 'Version code %s (native tree %s)' "$1" "$2"
+ }
+
+ # android_live_description <version code> <native hash> <PR number>
+ android_live_description() {
+ printf 'Version code %s is live on Google Play (native tree %s, PR #%s)' "$1" "$2" "$3"
+ }
+
+ # commit_status <sha> <context>: `<state> <description>` of the commit's latest
+ # status with that context, or nothing.
+ commit_status() {
+ gh api "repos/${GH_REPO}/commits/$1/status" \
+ --jq ".statuses[] | select(.context == \"$2\") | \"\(.state) \(.description)\""
+ }
+
+ # pr_commit_statuses <context>: `<sha> <state> <description>` for each of PR
+ # #PR_NUMBER's last 100 commits that has a status with that context (its
+ # latest one), states in lower case like the REST API's.
+ pr_commit_statuses() {
+ gh api graphql -F owner="${GH_REPO%%/*}" -F name="${GH_REPO#*/}" -F pr="$PR_NUMBER" -F context="$1" \
+ -f query='query($owner: String!, $name: String!, $pr: Int!, $context: String!) {
+ repository(owner: $owner, name: $name) {
+ pullRequest(number: $pr) {
+ commits(last: 100) { nodes { commit { oid status { context(name: $context) { state description } } } } }
+ }
+ }
+ }' \
+ --jq '.data.repository.pullRequest.commits.nodes[].commit
+ | select(.status.context != null)
+ | "\(.oid) \(.status.context.state | ascii_downcase) \(.status.context.description)"'
+ }
+
+ # set_commit_status <sha> <context> <state> <description>, linking this run.
+ set_commit_status() {
+ gh api "repos/${GH_REPO}/statuses/$1" -f context="$2" -f state="$3" -f description="$4" \
+ -f target_url="${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" >/dev/null
+ }
+ # ------------------------------------------------------------------------------
set -euo pipefail
- bun scripts/android-play-status.mjs --version-code "$VERSION_CODE" || true
+ # Was the stale bundle — version code $VERSION_CODE, released from
+ # $BEFORE_SHA or an earlier commit of PR #PR_NUMBER — submitted to Google
+ # Play production? This job runs the PR's code and cannot sign in to Play, so
+ # it reads the android-play/release status Android Play Publish sets on the
+ # commit it built: success means submitted, pending or failure that it may
+ # have been. A publish run still in progress may be promoting right now, so
+ # wait for it first. Outputs promoted=true|false, or nothing when unknown.
+ # BEFORE_SHA is checked directly because a force-push drops it from the PR.
+ deadline=$(( $(date +%s) + 10 * 60 ))
+ while true; do
+ if ! running=$(gh run list --repo "$GH_REPO" --workflow android-play-publish.yml --json status \
+ --jq '[.[] | select(.status != "completed")] | length'); then
+ echo "Could not list Android Play Publish runs; production status unknown."
+ exit 0
+ fi
+ if [[ "$running" == 0 ]]; then
+ break
+ fi
+ if (( $(date +%s) > deadline )); then
+ echo "An Android Play Publish run is still in progress; production status unknown."
+ exit 0
+ fi
+ echo "Waiting for ${running} Android Play Publish run(s) to finish."
+ sleep 15
+ done
+ if ! before=$(commit_status "$BEFORE_SHA" android-play/release) || ! others=$(pr_commit_statuses android-play/release); then
+ echo "Could not read android-play/release statuses; production status unknown."
+ exit 0
+ fi
+ promoted=false
+ while read -r sha state description; do
+ [[ "$description" == "Version code ${VERSION_CODE} ("* ]] || continue
+ echo "${sha:0:10}: android-play/release ${state}: ${description}"
+ if [[ "$state" == success ]]; then
+ promoted=true
+ break
+ fi
+ promoted=unknown
+ done < <({ [[ -z "$before" ]] || printf '%s %s\n' "$BEFORE_SHA" "$before"; } && printf '%s\n' "$others")
+ if [[ "$promoted" == unknown ]]; then
+ echo "Android Play Publish may have promoted version code ${VERSION_CODE}: production status unknown."
+ else
+ echo "promoted=${promoted}" >> "$GITHUB_OUTPUT"
+ echo "Version code ${VERSION_CODE} submitted to production: ${promoted}."
+ fi
shell: bash
env:
+ BEFORE_SHA: ${{ github.event.before }}
VERSION_CODE: ${{ steps.detect.outputs.version_code }}
- GOOGLE_PLAY_ACCESS_TOKEN: ${{ steps.auth.outputs.access_token }}
- working-directory: apps/web
- name: Remove the android-update label
if: always() && steps.detect.outputs.changed == 'true'
run: gh pr edit "$PR_NUMBER" --repo "$GH_REPO" --remove-label android-update
@@ -140,9 +226,9 @@ jobs:
if [[ "$PROMOTED" == "true" ]]; then
body="🚨 Android native changes were pushed to this PR after version code ${VERSION_CODE} had already been promoted to Google Play production, so that bundle is (or is about to be) live with native code this PR no longer matches. A Play release cannot be withdrawn: bump (\`${bump}\`), commit, re-add the \`android-update\` label, and ship the follow-up as soon as possible. The label was removed."
elif [[ "$PROMOTED" == "false" ]]; then
- body="🤖 Android native code changed after this PR's Play release started. Google Play reports that version code ${VERSION_CODE} has not been promoted to production. The \`android-update\` label was removed; any bundle on the internal track remains there for testers. Once in-progress release runs have stopped and the PR is ready again, bump (\`${bump}\`), commit, push, and re-add \`android-update\`."
+ body="🤖 Android native code changed after this PR's Play release started. Android Play Publish did not submit version code ${VERSION_CODE} to production. The \`android-update\` label was removed; any bundle on the internal track remains there for testers. Once in-progress release runs have stopped and the PR is ready again, bump (\`${bump}\`), commit, push, and re-add \`android-update\`."
else
- body="⚠️ Android native code changed or could not be compared with this PR's prior release, and Google Play production status could not be verified. The prior bundle may already be in review or live. The \`android-update\` label was removed. Keep the reviewed-SHA authentication restriction and verify production status in Play Console or through a check from an approved revision. Treat the prior release as potentially live until verified."
+ body="⚠️ Android native code changed or could not be compared with this PR's prior release, and whether that release was submitted to Google Play production could not be determined. The prior bundle may already be in review or live. The \`android-update\` label was removed. Check the production track in Play Console, and treat the prior release as potentially live until you have."
fi
gh pr comment "$PR_NUMBER" --repo "$GH_REPO" --body "$body"
shell: bash
diff --git a/.github/workflows/android-release-watch.yml b/.github/workflows/android-release-watch.yml
index a7ca8afe05..a503ba9a52 100644
--- a/.github/workflows/android-release-watch.yml
+++ b/.github/workflows/android-release-watch.yml
@@ -9,6 +9,7 @@ permissions:
actions: write
contents: read
pull-requests: write
+ statuses: write
id-token: write
jobs:
watch:
@@ -70,21 +71,77 @@ jobs:
fetch -q --depth=1 origin "$1"
}
# ------------------------------------------------------------------------------
+ # --- Android Play commit statuses ---------------------------------------------
+ # Only workflows that run main's copy may sign in to Google Play, so they
+ # record what they learn as commit statuses on the PR's commits, where the
+ # PR-side jobs (the merge gate, the drift check) read it:
+ #
+ # android-play/release set by Android Play Publish on the commit it built:
+ # pending just before the production promotion, then
+ # success or failure.
+ # android-play/live set by Android Release Watch on the PR head once the
+ # release is live on production.
+ #
+ # Readers match the descriptions exactly, so they are built only here.
+ # Needs GH_TOKEN and GH_REPO; pr_commit_statuses also PR_NUMBER.
+
+ # android_release_description <version code> <native hash>
+ android_release_description() {
+ printf 'Version code %s (native tree %s)' "$1" "$2"
+ }
+
+ # android_live_description <version code> <native hash> <PR number>
+ android_live_description() {
+ printf 'Version code %s is live on Google Play (native tree %s, PR #%s)' "$1" "$2" "$3"
+ }
+
+ # commit_status <sha> <context>: `<state> <description>` of the commit's latest
+ # status with that context, or nothing.
+ commit_status() {
+ gh api "repos/${GH_REPO}/commits/$1/status" \
+ --jq ".statuses[] | select(.context == \"$2\") | \"\(.state) \(.description)\""
+ }
+
+ # pr_commit_statuses <context>: `<sha> <state> <description>` for each of PR
+ # #PR_NUMBER's last 100 commits that has a status with that context (its
+ # latest one), states in lower case like the REST API's.
+ pr_commit_statuses() {
+ gh api graphql -F owner="${GH_REPO%%/*}" -F name="${GH_REPO#*/}" -F pr="$PR_NUMBER" -F context="$1" \
+ -f query='query($owner: String!, $name: String!, $pr: Int!, $context: String!) {
+ repository(owner: $owner, name: $name) {
+ pullRequest(number: $pr) {
+ commits(last: 100) { nodes { commit { oid status { context(name: $context) { state description } } } } }
+ }
+ }
+ }' \
+ --jq '.data.repository.pullRequest.commits.nodes[].commit
+ | select(.status.context != null)
+ | "\(.oid) \(.status.context.state | ascii_downcase) \(.status.context.description)"'
+ }
+
+ # set_commit_status <sha> <context> <state> <description>, linking this run.
+ set_commit_status() {
+ gh api "repos/${GH_REPO}/statuses/$1" -f context="$2" -f state="$3" -f description="$4" \
+ -f target_url="${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" >/dev/null
+ }
+ # ------------------------------------------------------------------------------
set -euo pipefail
# For each open PR labeled `android-update` (PRS: [{number, sha, merge}]), ask
# Google Play whether the version code committed at the PR head is live on
# production, built from the Android native code of the PR's merge result
# (`merge` is GitHub's test merge commit; the gate hashes the same). When it
- # is, and the PR's latest `Android Native Check` job (of the web app PR checks
- # run) failed — it fails until the release is live — re-run that job so the
- # gate, and the `Web App Status Check` that depends on it, go green without
- # anyone clicking "Re-run". GH_TOKEN needs actions:write + pull-requests:write;
- # GOOGLE_PLAY_ACCESS_TOKEN the androidpublisher scope.
+ # is, mark the PR head `android-play/live` (the gate cannot ask Play, so it
+ # reads that status), and if the PR's latest `Android Native Check` job (of
+ # the web app PR checks run) failed — it fails until the release is live —
+ # re-run that job so the gate, and the `Web App Status Check` that depends on
+ # it, go green without anyone clicking "Re-run". GH_TOKEN needs actions:write,
+ # pull-requests:write and statuses:write; GOOGLE_PLAY_ACCESS_TOKEN the
+ # androidpublisher scope.
cd apps/web
conf_path="apps/web/tauri/src-tauri/tauri.android.conf.json"
check_pr() {
- local pr=$1 number sha merge native_hash version_code run run_id status run_url job conclusion job_id reruns
+ local pr=$1 number sha merge native_hash version_code live run run_id status run_url job conclusion job_id reruns
number=$(jq -r '.number' <<<"$pr")
sha=$(jq -r '.sha' <<<"$pr")
merge=$(jq -r '.merge // empty' <<<"$pr")
@@ -104,6 +161,13 @@ jobs:
return 0
fi
echo " live on Google Play production"
+ live=$(android_live_description "$version_code" "$native_hash" "$number")
+ if [[ "$(commit_status "$sha" android-play/live)" == "success ${live}" ]]; then
+ echo " ${sha:0:10} already marked android-play/live"
+ else
+ set_commit_status "$sha" android-play/live success "$live"
+ echo " marked ${sha:0:10} android-play/live"
+ fi
run=$(gh run list --workflow web-app-check-main.yml --commit "$sha" \
--json databaseId,status,url --limit 1 --jq '.[0] // empty')
diff --git a/.github/workflows/ios-app-store-release.yml b/.github/workflows/ios-app-store-release.yml
index fa3a6789bb..d89dc60105 100644
--- a/.github/workflows/ios-app-store-release.yml
+++ b/.github/workflows/ios-app-store-release.yml
@@ -148,8 +148,9 @@ jobs:
# ------------------------------------------------------------------------------
# --- merge result native check ------------------------------------------------
# merge_result_native_check <hash> <listing> <fetch>: is the native code of
- # PR #PR_NUMBER's merge result the native code of HEAD, the code this run
- # built or is about to build? The merge gate hashes the merge result, so a
+ # PR #PR_NUMBER's merge result the native code of the commit this run built
+ # or is about to build — BUILT_SHA when set (a job that checked out other
+ # code, such as main's, to judge it), else HEAD? The merge gate hashes the merge result, so a
# build that differs from it could never pass the gate. <hash> / <listing>
# print a commit's native hash / the listing behind it; <fetch> makes a
# commit available (the iOS and Android helpers differ). Needs GH_TOKEN,
@@ -166,7 +167,7 @@ jobs:
# Callers run this under `if !`, which turns off `set -e` here, so every
# lookup is checked: an empty commit hashes the same on both sides and would
# pass an unchecked comparison.
- built=$(git rev-parse HEAD)
+ built=${BUILT_SHA:-$(git rev-parse HEAD)}
if ! built_hash=$($hash "$built"); then
echo "Could not hash this build's native code (${built:0:10})." >&2
return 1
@@ -537,8 +538,9 @@ jobs:
# ------------------------------------------------------------------------------
# --- merge result native check ------------------------------------------------
# merge_result_native_check <hash> <listing> <fetch>: is the native code of
- # PR #PR_NUMBER's merge result the native code of HEAD, the code this run
- # built or is about to build? The merge gate hashes the merge result, so a
+ # PR #PR_NUMBER's merge result the native code of the commit this run built
+ # or is about to build — BUILT_SHA when set (a job that checked out other
+ # code, such as main's, to judge it), else HEAD? The merge gate hashes the merge result, so a
# build that differs from it could never pass the gate. <hash> / <listing>
# print a commit's native hash / the listing behind it; <fetch> makes a
# commit available (the iOS and Android helpers differ). Needs GH_TOKEN,
@@ -555,7 +557,7 @@ jobs:
# Callers run this under `if !`, which turns off `set -e` here, so every
# lookup is checked: an empty commit hashes the same on both sides and would
# pass an unchecked comparison.
- built=$(git rev-parse HEAD)
+ built=${BUILT_SHA:-$(git rev-parse HEAD)}
if ! built_hash=$($hash "$built"); then
echo "Could not hash this build's native code (${built:0:10})." >&2
return 1
diff --git a/.github/workflows/release-label-check.yml b/.github/workflows/release-label-check.yml
index dd1e251eee..eb7fbcaef1 100644
--- a/.github/workflows/release-label-check.yml
+++ b/.github/workflows/release-label-check.yml
@@ -93,7 +93,7 @@ jobs:
steps="builds the app, uploads it to TestFlight and submits it for App Review"
else
what="Android version code $(jq -r '.bundle.android.versionCode' <<<"$conf")"
- steps="builds the App Bundle, uploads it to the internal track and promotes it to production"
+ steps="builds the App Bundle, and **Android Play Publish** uploads it to the internal track and promotes it to production"
fi
gh pr comment "$PR_NUMBER" --repo "$GH_REPO" --body "🚀 **${WORKFLOW}** started for ${what} at ${HEAD_SHA:0:10} ([workflow run](${url})). It ${steps}, then comments here with the result."
echo "PR #${PR_NUMBER}: ${WORKFLOW} started for ${what}: ${url}"
diff --git a/.github/workflows/web-app-check-main.yml b/.github/workflows/web-app-check-main.yml
index 26d332ab19..41ce717388 100644
--- a/.github/workflows/web-app-check-main.yml
+++ b/.github/workflows/web-app-check-main.yml
@@ -80,7 +80,7 @@ jobs:
permissions:
contents: read
pull-requests: read
- id-token: write
+ statuses: read
steps:
- name: Checkout PR merge commit
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10
@@ -124,17 +124,6 @@ jobs:
bun scripts/android-version-check.mjs --skip-release "$base"
shell: bash
working-directory: apps/web
- - id: auth
- name: Authenticate to Google Play
- if: steps.android-version.outputs.changed == 'true' && steps.labels.outputs.skip != 'true'
- uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093
- with:
- workload_identity_provider: ${{ vars.GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER }}
- service_account: ${{ vars.GOOGLE_PLAY_SERVICE_ACCOUNT }}
- token_format: access_token
- access_token_scopes: https://www.googleapis.com/auth/androidpublisher
- create_credentials_file: 'false'
- export_environment_variables: 'false'
- name: Require the Play release to be live
if: steps.android-version.outputs.changed == 'true' && steps.labels.outputs.skip != 'true'
run: |
@@ -182,20 +171,107 @@ jobs:
done
}
# ------------------------------------------------------------------------------
+ # --- Android Play commit statuses ---------------------------------------------
+ # Only workflows that run main's copy may sign in to Google Play, so they
+ # record what they learn as commit statuses on the PR's commits, where the
+ # PR-side jobs (the merge gate, the drift check) read it:
+ #
+ # android-play/release set by Android Play Publish on the commit it built:
+ # pending just before the production promotion, then
+ # success or failure.
+ # android-play/live set by Android Release Watch on the PR head once the
+ # release is live on production.
+ #
+ # Readers match the descriptions exactly, so they are built only here.
+ # Needs GH_TOKEN and GH_REPO; pr_commit_statuses also PR_NUMBER.
+
+ # android_release_description <version code> <native hash>
+ android_release_description() {
+ printf 'Version code %s (native tree %s)' "$1" "$2"
+ }
+
+ # android_live_description <version code> <native hash> <PR number>
+ android_live_description() {
+ printf 'Version code %s is live on Google Play (native tree %s, PR #%s)' "$1" "$2" "$3"
+ }
+
+ # commit_status <sha> <context>: `<state> <description>` of the commit's latest
+ # status with that context, or nothing.
+ commit_status() {
+ gh api "repos/${GH_REPO}/commits/$1/status" \
+ --jq ".statuses[] | select(.context == \"$2\") | \"\(.state) \(.description)\""
+ }
+
+ # pr_commit_statuses <context>: `<sha> <state> <description>` for each of PR
+ # #PR_NUMBER's last 100 commits that has a status with that context (its
+ # latest one), states in lower case like the REST API's.
+ pr_commit_statuses() {
+ gh api graphql -F owner="${GH_REPO%%/*}" -F name="${GH_REPO#*/}" -F pr="$PR_NUMBER" -F context="$1" \
+ -f query='query($owner: String!, $name: String!, $pr: Int!, $context: String!) {
+ repository(owner: $owner, name: $name) {
+ pullRequest(number: $pr) {
+ commits(last: 100) { nodes { commit { oid status { context(name: $context) { state description } } } } }
+ }
+ }
+ }' \
+ --jq '.data.repository.pullRequest.commits.nodes[].commit
+ | select(.status.context != null)
+ | "\(.oid) \(.status.context.state | ascii_downcase) \(.status.context.description)"'
+ }
+
+ # set_commit_status <sha> <context> <state> <description>, linking this run.
+ set_commit_status() {
+ gh api "repos/${GH_REPO}/statuses/$1" -f context="$2" -f state="$3" -f description="$4" \
+ -f target_url="${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" >/dev/null
+ }
+ # ------------------------------------------------------------------------------
set -euo pipefail
+ # The Android merge gate proper: version code $VERSION_CODE must be live on
+ # Google Play production, built from the Android native code of PR
+ # #PR_NUMBER's *current* merge result (fetched through the API: a re-run
+ # checks out the merge commit of the run's original event, which may predate
+ # native code landing on main). This job cannot sign in to Play — only
+ # workflows that run main's copy can — so it reads the `android-play/live`
+ # status that Android Release Watch sets once the release is live. Any of the
+ # PR's commits counts: web-only pushes after the release keep it valid, and
+ # the native hash in the description pins it to this merge result.
merge=$(pr_merge_commit)
gh_fetch "$merge"
native_hash=$(bun scripts/android-native.mjs hash "$merge")
echo "Merge result ${merge:0:10}: Android native hash ${native_hash}"
- bun scripts/android-play-status.mjs --version-code "$VERSION_CODE" --require-live \
- --native-hash "$native_hash" --pr "$PR_NUMBER"
+ want=$(android_live_description "$VERSION_CODE" "$native_hash" "$PR_NUMBER")
+ statuses=$(pr_commit_statuses android-play/live)
+ while read -r sha state description; do
+ if [[ "$state" == success && "$description" == "$want" ]]; then
+ echo "${sha:0:10} is marked android-play/live: ${description}."
+ exit 0
+ fi
+ done <<<"$statuses"
+ echo "Android native changes require version code ${VERSION_CODE} to be live on Google Play before merging," \
+ "built from native tree ${native_hash}, but no commit of this PR is marked so (android-play/live)." >&2
+ if [[ -n "$statuses" ]]; then
+ echo "android-play/live statuses on this PR's commits:" >&2
+ while read -r sha state description; do
+ echo " ${sha:0:10} ${state}: ${description}" >&2
+ done <<<"$statuses"
+ fi
+ cat >&2 <<'EOF'
+ - Not started yet? Add the `android-update` label to the PR to build, upload
+ and promote it.
+ - Promoted? Wait for Google review; the `Android Release Watch` workflow marks
+ the PR and re-runs this check within half an hour of the release.
+ - Native code changed since the release (pushed to the PR, or landed on main)?
+ Bump (`just android-bump`), commit, re-add `android-update`.
+ - If the native change doesn't break the native/web contract, add the
+ `skip-android-update` label instead.
+ EOF
+ exit 1
shell: bash
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PR_NUMBER: ${{ github.event.pull_request.number }}
VERSION_CODE: ${{ steps.android-version.outputs.version_code }}
- GOOGLE_PLAY_ACCESS_TOKEN: ${{ steps.auth.outputs.access_token }}
working-directory: apps/web
- name: Skipped via label
if: steps.labels.outputs.skip == 'true'
diff --git a/apps/web/scripts/android-native.mjs b/apps/web/scripts/android-native.mjs
index e74f60eabc..39811e3910 100644
--- a/apps/web/scripts/android-native.mjs
+++ b/apps/web/scripts/android-native.mjs
@@ -1,8 +1,8 @@
// What "the Android native code" is, shared by the PR gate
-// (android-version-check.mjs), the Play release workflow's preconditions,
-// head guard and provenance stamp, the drift check and the watcher (all
-// through the `hash` CLI below) so they can never disagree about whether a
-// change is native.
+// (android-version-check.mjs), the Play release workflow's preconditions and
+// head guard, the publisher's head guard and provenance stamp, the drift
+// check and the watcher (all through the `hash` CLI below) so they can never
+// disagree about whether a change is native.
//
// It is every tracked file under apps/web/tauri except what never reaches
// the Android binary — iOS, macOS, Linux, Windows and desktop-only paths by
diff --git a/docs/development/android.md b/docs/development/android.md
index 93e5636ea2..e028a031da 100644
--- a/docs/development/android.md
+++ b/docs/development/android.md
@@ -138,19 +138,31 @@ its fingerprint to production associations before testing Play-installed links.
Android releases are driven from pull requests, like iOS (see
`apps/web/docs/ios-releases.md`). Unlike iOS, whose approved version is held
until the prod deploy, they are not tied to the production deployment cycle.
-Three generated workflows plus the `Android Native Check`
-job of the web app PR checks enforce it:
+Four generated workflows plus the `Android Native Check`
+job of the web app PR checks enforce it.
+
+Only workflows that run `main`'s copy sign in to Google Play: **`Android Play
+Publish`** and **`Android Release Watch`** (plus the manual
+`publish-android-play.yml`). Workflows on `pull_request` events run the PR's
+own copy of the workflow and its scripts, so they never get the publishing
+identity. They read what the `main`-side workflows learned from Play as commit
+statuses on the PR's commits: `android-play/release` (set by the publisher
+around the production promotion) and `android-play/live` (set by the watcher
+once the release is live).
**`Android Native Check`** runs on every PR against `main`. Its native tree
excludes platform-specific desktop/iOS files and Markdown docs, which do not
ship in the Android binary (`apps/web/scripts/android-native.mjs` defines
what counts). When the Android native code changed, it requires a
-`versionCode` bump and asks Google Play whether that version code is a
-production release that Google has **published** (through review and
-available to users — the edit API's `status: completed` only describes the
-rollout, so the gate also reads the release list's `releaseLifecycleState`),
-built from the native code of the PR's merge result. Until both hold the
-check fails and the required `Web App Status Check` fails with it.
+`versionCode` bump and a commit of the PR marked `android-play/live` for that
+version code, the native hash of the PR's current merge result, and the PR.
+The watcher sets that status only once Google has **published** the release
+(through review and available to users; the edit API's `status: completed`
+only describes the rollout, so the watcher also reads the release list's
+`releaseLifecycleState`) with a provenance stamp matching the merge result.
+Until then the check fails and the required `Web App Status Check` fails with
+it. Web-only pushes after the release keep it valid: the status on an earlier
+commit still matches.
Add **`skip-android-update`** instead for native changes that don't break
the native/web contract: it skips the whole gate, bump included, like
@@ -171,7 +183,8 @@ To release:
The gate accepts only those two floors: the new versionCode or the base
branch's. A PR without Android native changes may raise the floor only as
far as the base branch's versionCode.
-2. Add the **`android-update`** label once the PR is ready to merge. The
+2. Add the **`android-update`** label once the PR is ready to merge. Adding
+ it is the release decision: nothing else approves it. The
**`Android Play Release`** workflow (`.github/workflows/android-play-release.yml`)
first refuses drafts, PRs with failing checks (pending ones are waited on,
up to 30 minutes), PRs without a bump, and PRs whose head lacks Android
@@ -185,14 +198,30 @@ To release:
runner (Android SDK, Nix, signing and Firebase config from Doppler
`android-release/prd`), verifies it with bundletool,
checks again that neither the PR head nor `main` changed native code
- during the build, uploads it to the **internal** track with
- `status=completed`, and promotes it to **production** as a full rollout
- (Google review applies). The bundle and R8 mapping are kept as a workflow
- artifact for 90 days. The release notes carry a provenance stamp,
- `native tree <hash> for PR #<n>`, the twin of the iOS TestFlight stamp.
- The run comments the outcome on the PR (a failure names the step that
- failed and, for the checking steps, quotes the end of its output);
- remove and re-add the label to retry. Click **Enable auto-merge** on the
+ during the build, and keeps the bundle and R8 mapping as the
+ `android-release` workflow artifact (90 days). When the build succeeds,
+ **`Android Play Publish`** (`.github/workflows/android-play-publish.yml`,
+ a `workflow_run` workflow, so `main`'s copy) takes over. It treats the
+ build and its artifact as untrusted, since PR code produced them, and
+ publishes only a build tied to whoever added the label: the build job
+ succeeded, the branch is the head of one open same-repository PR into
+ `main`, the PR still carries the label, and its latest label event is an
+ add by a person with write access who started the build run within
+ minutes of adding it. GitHub doesn't record which PR activity created a
+ run, so a branch that edits its release workflow could also build on that
+ person's other activity in the window; that grants nothing beyond adding
+ the label, since pushing to the branch already needs write access.
+ It then repeats the head guard, writes the release notes' provenance
+ stamp (`native tree <hash> for PR #<n>`, the twin of the iOS TestFlight
+ stamp) from `main`'s hashing script, uploads the bundle to the
+ **internal** track with `status=completed`, checks the native code once
+ more, and promotes it to **production** as a full rollout (Google review
+ applies), recording the promotion as the `android-play/release` status.
+ A failed build comments on the PR; otherwise the publisher comments the
+ outcome (a failure names the step that failed and, for the checking
+ steps, quotes the end of its output). Remove and re-add the label to
+ retry; once the upload succeeded the version code is used up, so bump
+ first. Click **Enable auto-merge** on the
PR to merge the moment it is live. The label only works on a PR that is
mergeable: GitHub does not run `pull_request` workflows on a PR that
conflicts with `main`, so the release never starts there. The **`Release Label Check`** workflow
@@ -202,19 +231,22 @@ To release:
instead comments that the release started, with the version in flight
and a link to the run.
3. Wait for Google. The **`Android Release Watch`** workflow (every 30
- minutes) notices the version code being published on production, re-runs
- the PR's failed `Android Native Check` job, and comments; the PR merges if
- auto-merge is on.
+ minutes) notices the version code being published on production, marks
+ the PR head `android-play/live`, re-runs the PR's failed
+ `Android Native Check` job, and comments; the PR merges if auto-merge is
+ on.
4. Pushes after the label: web-only commits need nothing. Native commits make
the bundle stale: **`Android Release Drift`** cancels an in-progress build,
removes the label and comments. A Play production release cannot be
withdrawn once submitted, so if the stale bundle was already promoted the
- comment says so and the follow-up should ship as soon as possible. If the
- previous native tree cannot be verified (for example, after a force-push),
- drift skips the Play lookup and reports production status as unknown; the
- new head's version code cannot identify the prior release. Authentication
- or Play lookup failures also report unknown status. Keep the reviewed-SHA
- restriction and verify through an approved check or Play Console before
+ comment says so and the follow-up should ship as soon as possible. Drift
+ cannot sign in to Play; after waiting for publish runs in progress, it
+ reads the `android-play/release` status on the old head and the PR's
+ commits: success means promoted, pending or failure that it may have
+ been. If the previous native tree cannot be verified (for example, after
+ a force-push), drift reports production status as unknown; the new head's
+ version code cannot identify the prior release. A failed lookup also
+ reports unknown status. Check the production track in Play Console before
treating the prior release as stopped.
Play is the source of truth for what is live; nothing ties Android bundles
@@ -248,9 +280,10 @@ bundle is uploaded; an AAB cannot be installed directly on a device.
### Google Play publishing
`.github/workflows/publish-android-play.yml` runs from `main` and is the
-manual fallback. Routine releases go through the `Android Play Release`
-workflow described above, which uploads the PR's bundle to internal testing
-and promotes it to production itself; the publishing workflow is for
+manual fallback. Routine releases go through the `Android Play Release` and
+`Android Play Publish` workflows described above, which upload the PR's
+bundle to internal testing and promote it to production; the manual
+publishing workflow is for
promoting a version code by hand or uploading a bundle attached to a GitHub
release.
@@ -311,18 +344,39 @@ attribute.repository_id=assertion.repository_id
Use issuer `https://token.actions.githubusercontent.com`. Restrict the provider's
attribute condition to the numeric repository and owner IDs (available from
-`gh api repos/macro-inc/macro --jq '{repository: .id, owner: .owner.id}'`).
-The initial condition below permits only the manual publishing workflow on
-`main`; automatic PR releases also need the explicit grants described in
-"Authorize an approved PR release" below:
+`gh api repos/macro-inc/macro --jq '{repository: .id, owner: .owner.id}'`)
+and to the three workflows that run `main`'s copy, each for the events it
+runs on: the manual publisher, the watcher, and `Android Play Publish`
+(`workflow_run` workflows always run from the default branch, so their token
+carries `main`'s ref and subject). Save it as `play-condition.cel`:
```text
assertion.repository_id == '1092407718' &&
assertion.repository_owner_id == '65687018' &&
-assertion.workflow_ref == 'macro-inc/macro/.github/workflows/publish-android-play.yml@refs/heads/main' &&
-assertion.sub == 'repo:macro-inc/macro:ref:refs/heads/main'
+assertion.ref == 'refs/heads/main' &&
+assertion.sub == 'repo:macro-inc/macro:ref:refs/heads/main' &&
+(
+ (
+ assertion.workflow_ref == 'macro-inc/macro/.github/workflows/publish-android-play.yml@refs/heads/main' &&
+ assertion.event_name == 'workflow_dispatch'
+ ) ||
+ (
+ assertion.workflow_ref == 'macro-inc/macro/.github/workflows/android-release-watch.yml@refs/heads/main' &&
+ assertion.event_name in ['schedule', 'workflow_dispatch']
+ ) ||
+ (
+ assertion.workflow_ref == 'macro-inc/macro/.github/workflows/android-play-publish.yml@refs/heads/main' &&
+ assertion.event_name == 'workflow_run'
+ )
+)
```
+No workflow on `pull_request` events is admitted, and none needs to be: those
+run the PR's code, which must never get the publishing identity. The
+condition never changes per PR. Change it only when one of these three
+workflow files is renamed, or a workflow that runs `main`'s copy newly needs
+Play; never add a `pull_request` alternative.
+
On the publishing service account, grant `roles/iam.workloadIdentityUser` to:
```text
@@ -356,7 +410,7 @@ gcloud iam workload-identity-pools providers create-oidc macro \
--workload-identity-pool=github-play \
--issuer-uri=https://token.actions.githubusercontent.com \
--attribute-mapping='google.subject=assertion.sub,attribute.repository_id=assertion.repository_id' \
- --attribute-condition="assertion.repository_id == '1092407718' && assertion.repository_owner_id == '65687018' && assertion.workflow_ref == 'macro-inc/macro/.github/workflows/publish-android-play.yml@refs/heads/main' && assertion.sub == 'repo:macro-inc/macro:ref:refs/heads/main'"
+ --attribute-condition="$(cat play-condition.cel)"
gcloud iam service-accounts add-iam-policy-binding \
@@ -373,90 +427,37 @@ gh variable set GOOGLE_PLAY_SERVICE_ACCOUNT --repo macro-inc/macro \
```
-#### Authorize an approved PR release
-
-The initial provider condition rejects the PR-based native check and release
-workflows. Before releasing a reviewed same-repository PR, an identity
-administrator must extend that condition with narrowly scoped alternatives:
-
-- Keep the numeric repository and owner ID checks around every alternative,
- and retain the existing manual publisher on `main`.
-- Permit `android-release-watch.yml@refs/heads/main` only with the main ref and
- main subject, for `schedule` or `workflow_dispatch` events.
-- Permit the specific approved `refs/pull/<PR_NUMBER>/merge` only for
- `pull_request` events, the `repo:macro-inc/macro:pull_request` subject,
- `base_ref == 'main'`, the reviewed merge commit in `assertion.sha`, and these
- exact workflow paths at that same merge ref:
- `web-app-check-main.yml`, `android-play-release.yml`, and
- `android-release-drift.yml` under `macro-inc/macro/.github/workflows/`.
-
-Check the PR's head repository and review its merge commit before granting access.
-Do not replace the approved PR ref or SHA with a wildcard: PR workflows execute
-the proposed code with the publishing identity. For `pull_request` workflows,
-`assertion.sha` identifies the event's merge commit, not the PR head. A later push
-or base-branch update creates a different merge commit; review the changes before
-updating the grant. Reruns retain the original event SHA, and release jobs request
-credentials after building. Retain each reviewed event SHA in an explicit
-`assertion.sha in [...]` allowlist while its approved gate, release, or drift run
-still needs credentials, then remove it. Remove the PR's alternative after it
-merges or closes. Keep the main watcher permission so it can verify releases and
-rerun native gates.
-
-Back up the existing provider, then create the complete condition below. Replace
-`<PR_NUMBER>` and `<REVIEWED_MERGE_SHA>` with the approved PR number and full
-40-character merge commit SHA. This example preserves the initial publisher and
-adds the watcher; preserve any other independently approved grants already in
-`provider-before.json` instead of overwriting them.
+#### Update the provider condition
+
+To replace the provider's condition (for example, to move an older provider
+that still carries per-PR grants to the one above), back the provider up and
+update it with the complete condition; the attribute mappings and the service
+account binding stay as they are:
```sh
gcloud iam workload-identity-pools providers describe macro \
--project=macro-435922 --location=global \
--workload-identity-pool=github-play --format=json > provider-before.json
-cat > approved-play-condition.cel <<'CEL'
-assertion.repository_id == '1092407718' &&
-assertion.repository_owner_id == '65687018' &&
-(
- (
- assertion.workflow_ref == 'macro-inc/macro/.github/workflows/publish-android-play.yml@refs/heads/main' &&
- assertion.sub == 'repo:macro-inc/macro:ref:refs/heads/main'
- ) ||
- (
- assertion.workflow_ref == 'macro-inc/macro/.github/workflows/android-release-watch.yml@refs/heads/main' &&
- assertion.ref == 'refs/heads/main' &&
- assertion.sub == 'repo:macro-inc/macro:ref:refs/heads/main' &&
- assertion.event_name in ['schedule', 'workflow_dispatch']
- ) ||
- (
- assertion.event_name == 'pull_request' &&
- assertion.sub == 'repo:macro-inc/macro:pull_request' &&
- assertion.ref == 'refs/pull/<PR_NUMBER>/merge' &&
- assertion.base_ref == 'main' &&
- assertion.sha == '<REVIEWED_MERGE_SHA>' &&
- assertion.workflow_ref in [
- 'macro-inc/macro/.github/workflows/web-app-check-main.yml@refs/pull/<PR_NUMBER>/merge',
- 'macro-inc/macro/.github/workflows/android-play-release.yml@refs/pull/<PR_NUMBER>/merge',
- 'macro-inc/macro/.github/workflows/android-release-drift.yml@refs/pull/<PR_NUMBER>/merge'
- ]
- )
-)
-CEL
-
gcloud iam workload-identity-pools providers update-oidc macro \
--project=macro-435922 --location=global \
--workload-identity-pool=github-play \
- --attribute-condition="$(cat approved-play-condition.cel)"
+ --attribute-condition="$(cat play-condition.cel)"
```
-Keep the existing attribute mappings and service-account role binding. Verify the
-updated condition, then rerun the failed Android native-check job: successful
-authentication must reach the Play status check before triggering the release.
-See [GitHub's OIDC claims](https://docs.github.com/en/actions/reference/security/oidc)
-for the distinction between PR subjects and branch subjects.
+Update it before merging a change that adds or renames one of the admitted
+workflows: `workflow_run` workflows only run once they are on `main`, and the
+first run after the merge must be able to sign in. Google has no dry run
+for the condition, so check what it stored instead: the `attributeCondition`
+in `describe --format=json` must match `play-condition.cel`. The watcher
+signs in only while a PR carries `android-update`, so the first
+`Android Play Publish` run is the real test of the new alternative. See
+[GitHub's OIDC claims](https://docs.github.com/en/actions/reference/security/oidc)
+for the subject and ref each event carries.
#### Manual upload (fallback)
-The `Android Play Release` workflow uploads and promotes automatically. For a
+`Android Play Publish` uploads and promotes PR releases automatically. For a
manual upload, select **Publish Android to Google Play** in Actions, run from
`main`, select `operation=upload-internal`, and supply a published GitHub
release tag that carries Android artifacts (none are produced automatically
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows.rs b/tooling/xtask/crates/xtask_workflows/src/workflows.rs
index 20df6be8c0..67e775536f 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows.rs
@@ -9,6 +9,7 @@
//! files — [`runners`] (runner labels), [`vars`] (env / secrets / concurrency),
//! and [`steps`] (reusable step + job helpers).
+mod android_play_publish;
mod android_play_release;
mod android_release_drift;
mod android_release_watch;
@@ -345,6 +346,11 @@ const WORKFLOWS: &[WorkflowFile] = &[
file_name: "android-play-release.yml",
render_yaml: || render_gh_workflow(android_play_release::android_play_release)(),
},
+ WorkflowFile {
+ slug: "android_play_publish",
+ file_name: "android-play-publish.yml",
+ render_yaml: || render_gh_workflow(android_play_publish::android_play_publish)(),
+ },
WorkflowFile {
slug: "android_release_watch",
file_name: "android-release-watch.yml",
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/android_play_publish.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/android_play_publish.rs
new file mode 100644
index 0000000000..403344793f
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/android_play_publish.rs
@@ -0,0 +1,366 @@
+//! `Android Play Publish` — uploads the App Bundle an
+//! [`super::android_play_release`] run built to Google Play's internal track
+//! and promotes it to production (full rollout; Google review applies), the
+//! release the `Android Native Check` merge gate then waits on.
+//!
+//! The build and the publish are separate workflows because of the Play
+//! credential. `Android Play Release` runs on `pull_request` events, so it
+//! executes the PR's copy of the workflow and of every build script and
+//! dependency; giving it the publishing identity would hand that identity to
+//! whatever a PR proposes. This workflow runs on `workflow_run`, which GitHub
+//! always runs from `main`'s copy, so Google's Workload Identity provider
+//! admits it with a fixed condition (main's ref and this file; see
+//! "Keyless publishing credentials" in docs/development/android.md) instead
+//! of a grant per PR.
+//!
+//! It treats the build run and its artifact as untrusted. The `check` job
+//! publishes only a run that the `android-update` label started
+//! (`scripts/android_play_publish_verify.sh`): the label, added by a person
+//! with write access, is the release decision. The `publish` job then
+//! derives everything it tells Play from main's scripts and the PR's commit
+//! (version code, provenance stamp, head guard), passes the artifact's files
+//! to Play without running anything from them, and records the promotion as
+//! the `android-play/release` commit status that
+//! [`super::android_release_drift`] reads.
+//!
+//! Every completed `Android Play Release` run triggers this — the build
+//! workflow runs for every label added to a PR, its job skipping the others
+//! — so `check` ends quietly when there is nothing to publish, and only
+//! `publish` joins the per-branch concurrency group (a queued no-op run would
+//! otherwise cancel a pending publish).
+
+use gh_workflow::{
+ Concurrency, Event, Expression, Job, Level, Permissions, Run, Step, Use, Workflow, WorkflowRun,
+ WorkflowRunType,
+};
+
+use crate::workflows::{runners, steps};
+
+#[cfg(test)]
+mod test;
+
+/// The `publish` job's name, which its failure comment looks up.
+const PUBLISH_JOB_NAME: &str = "Android Play Publish";
+
+/// Build the workflow.
+pub fn android_play_publish() -> Workflow {
+ Workflow::new("Android Play Publish")
+ .on(Event::default().workflow_run(
+ WorkflowRun::default()
+ .add_type(WorkflowRunType::Completed)
+ .add_workflow("Android Play Release"),
+ ))
+ .add_job("check", check_job())
+ .add_job("publish", publish_job())
+}
+
+fn check_job() -> Job {
+ Job::default()
+ .name("Check the release request")
+ // The build job skips fork PRs, and fork runs never get here with a
+ // successful build; the head-repository test is belt and braces.
+ .cond(Expression::new(
+ "github.event.workflow_run.conclusion == 'success' && \
+ github.event.workflow_run.event == 'pull_request' && \
+ github.event.workflow_run.head_repository.full_name == github.repository",
+ ))
+ .runs_on(runners::Runner::TinyNoCache.to_string())
+ .timeout_minutes(10u32)
+ .permissions(
+ Permissions::default()
+ .actions(Level::Read)
+ .contents(Level::Read)
+ .issues(Level::Read)
+ .pull_requests(Level::Write),
+ )
+ .add_env(("GH_TOKEN", "${{ github.token }}"))
+ .add_env(("GH_REPO", "${{ github.repository }}"))
+ .add_output("publish", "${{ steps.verify.outputs.publish }}")
+ .add_output("pr_number", "${{ steps.verify.outputs.pr_number }}")
+ .add_output("version_code", "${{ steps.verify.outputs.version_code }}")
+ .add_output("release_name", "${{ steps.verify.outputs.release_name }}")
+ .add_step(steps::checkout(false, false))
+ .add_step(steps::setup_bun_pinned())
+ .add_step(verify())
+ .add_step(refusal_comment())
+}
+
+fn verify() -> Step<Run> {
+ steps::logged_run(
+ "Require a build the android-update label started",
+ concat!(
+ include_str!("scripts/android_git_fetch.sh"),
+ include_str!("scripts/android_play_publish_verify.sh")
+ ),
+ )
+ .id("verify")
+ .working_directory(xtask_paths::repo_dir!("apps/web"))
+ .add_env(("RUN_ID", "${{ github.event.workflow_run.id }}"))
+ .add_env((
+ "RUN_ATTEMPT",
+ "${{ github.event.workflow_run.run_attempt }}",
+ ))
+ .add_env(("RUN_PATH", "${{ github.event.workflow_run.path }}"))
+ .add_env(("RUN_ACTOR", "${{ github.event.workflow_run.actor.login }}"))
+ .add_env((
+ "RUN_CREATED_AT",
+ "${{ github.event.workflow_run.created_at }}",
+ ))
+ .add_env(("HEAD_SHA", "${{ github.event.workflow_run.head_sha }}"))
+ .add_env((
+ "HEAD_BRANCH",
+ "${{ github.event.workflow_run.head_branch }}",
+ ))
+}
+
+/// A refusal is worth telling the PR about once the PR is known.
+fn refusal_comment() -> Step<Run> {
+ Step::new("Comment on the PR")
+ .run(indoc::indoc! {r#"
+ set -euo pipefail
+ reason=$(sed -n 's/\x1b\[[0-9;]*m//g; s/^Not publishing run [0-9]*: //p' "$RUNNER_TEMP/last-step.log" | tail -n 1)
+ gh pr comment "$PR_NUMBER" --repo "$GH_REPO" --body "🤖 Android Play Publish did not publish [this Android Play Release build](${BUILD_URL}): ${reason:-see the [workflow run](${RUN_URL}).}
+
+ A person with write access can remove and re-add the \`android-update\` label to release the PR's current head."
+ "#})
+ .if_condition(Expression::new(
+ "failure() && steps.verify.outputs.pr_number != ''",
+ ))
+ .shell("bash")
+ .add_env(("PR_NUMBER", "${{ steps.verify.outputs.pr_number }}"))
+ .add_env(("BUILD_URL", "${{ github.event.workflow_run.html_url }}"))
+ .add_env((
+ "RUN_URL",
+ "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}",
+ ))
+}
+
+fn publish_job() -> Job {
+ Job::default()
+ .name(PUBLISH_JOB_NAME)
+ .add_needs("check")
+ .cond(Expression::new("needs.check.outputs.publish == 'true'"))
+ // A hosted image: the upload action and the promotion script need Node.
+ .runs_on("ubuntu-24.04")
+ .timeout_minutes(30u32)
+ // One release at a time per PR branch, queued rather than cancelled:
+ // a cancelled run can leave a promotion half-reported.
+ .concurrency(Concurrency::new(Expression::new(
+ "android-play-publish-${{ github.event.workflow_run.head_branch }}",
+ )))
+ .permissions(
+ Permissions::default()
+ // The artifact download and the failure comment's step lookup.
+ .actions(Level::Read)
+ .contents(Level::Read)
+ .id_token(Level::Write)
+ .pull_requests(Level::Write)
+ .statuses(Level::Write),
+ )
+ .add_env(("GH_TOKEN", "${{ github.token }}"))
+ .add_env(("GH_REPO", "${{ github.repository }}"))
+ .add_env(("PR_NUMBER", "${{ needs.check.outputs.pr_number }}"))
+ .add_env(("VERSION_CODE", "${{ needs.check.outputs.version_code }}"))
+ .add_env(("BUILT_SHA", "${{ github.event.workflow_run.head_sha }}"))
+ .add_env(("BASE_BRANCH", "main"))
+ .add_step(steps::checkout(false, false))
+ .add_step(steps::setup_bun_pinned())
+ .add_step(head_guard("upload"))
+ .add_step(provenance_stamp())
+ .add_step(download_artifact())
+ .add_step(pick_files())
+ .add_step(steps::google_play_auth(true))
+ .add_step(upload_internal())
+ .add_step(head_guard("promote"))
+ .add_step(mark_promotion_pending())
+ .add_step(promote_production())
+ .add_step(mark_promotion_result())
+ .add_step(pr_comment())
+}
+
+/// The PR's native code — and main's — must still be what was built: once
+/// before the upload, and again before the irreversible promotion.
+fn head_guard(stage: &str) -> Step<Run> {
+ let name = if stage == "promote" {
+ "Require the native code to be unchanged before promoting"
+ } else {
+ "Require the PR's Android native code to be unchanged since the build"
+ };
+ steps::logged_run(
+ name,
+ concat!(
+ include_str!("scripts/android_git_fetch.sh"),
+ include_str!("scripts/pr_merge_commit.sh"),
+ include_str!("scripts/merge_result_native_check.sh"),
+ include_str!("scripts/android_release_head_guard.sh")
+ ),
+ )
+ .working_directory(xtask_paths::repo_dir!("apps/web"))
+ .add_env(("GUARD_STAGE", stage))
+}
+
+/// The release notes carry the native hash and PR number, which the watcher
+/// compares against the merge result (the TestFlight stamp's twin). Computed
+/// here, from main's hashing script, not taken from the build.
+fn provenance_stamp() -> Step<Run> {
+ steps::logged_run(
+ "Write the provenance stamp as release notes",
+ indoc::indoc! {r#"
+ set -euo pipefail
+ hash=$(bun scripts/android-native.mjs hash "$BUILT_SHA")
+ mkdir -p "$RUNNER_TEMP/whatsnew"
+ printf 'native tree %s for PR #%s\n' "$hash" "$PR_NUMBER" > "$RUNNER_TEMP/whatsnew/whatsnew-en-US"
+ echo "native_hash=${hash}" >> "$GITHUB_OUTPUT"
+ echo "Stamp: native tree ${hash} for PR #${PR_NUMBER}"
+ "#},
+ )
+ .id("stamp")
+ .working_directory(xtask_paths::repo_dir!("apps/web"))
+}
+
+fn download_artifact() -> Step<Use> {
+ Step::new("Download the built App Bundle")
+ .uses(
+ "actions",
+ "download-artifact",
+ "634f93cb2916e3fdff6788551b99b062d0335ce0",
+ ) // v5
+ .add_with(("name", "android-release"))
+ .add_with(("run-id", "${{ github.event.workflow_run.id }}"))
+ .add_with(("github-token", "${{ github.token }}"))
+ .add_with(("path", "${{ runner.temp }}/android-release"))
+}
+
+/// The artifact was written by PR code: take exactly one bundle and one
+/// mapping with plain file names, as data for Play to check.
+fn pick_files() -> Step<Run> {
+ steps::logged_run(
+ "Pick the bundle and its R8 mapping",
+ indoc::indoc! {r#"
+ set -euo pipefail
+ dir="$RUNNER_TEMP/android-release"
+ mapfile -t bundles < <(find "$dir" -maxdepth 1 -type f -name '*.aab' -printf '%f\n')
+ mapfile -t mappings < <(find "$dir" -maxdepth 1 -type f -name '*-mapping.txt' -printf '%f\n')
+ if (( ${#bundles[@]} != 1 || ${#mappings[@]} != 1 )); then
+ echo "Expected one .aab and one -mapping.txt in the android-release artifact, found ${#bundles[@]} and ${#mappings[@]}." >&2
+ exit 1
+ fi
+ for name in "${bundles[0]}" "${mappings[0]}"; do
+ if [[ ! "$name" =~ ^[A-Za-z0-9._-]+$ ]]; then
+ echo "Refusing the artifact file name ${name}." >&2
+ exit 1
+ fi
+ done
+ echo "bundle=${dir}/${bundles[0]}" >> "$GITHUB_OUTPUT"
+ echo "mapping=${dir}/${mappings[0]}" >> "$GITHUB_OUTPUT"
+ echo "Bundle ${bundles[0]}, mapping ${mappings[0]}."
+ "#},
+ )
+ .id("artifact")
+}
+
+fn upload_internal() -> Step<Use> {
+ Step::new("Upload to internal testing")
+ .uses(
+ "r0adkll",
+ "upload-google-play",
+ "e738b9dd8f2476ea806d921b64aacd24f34515a5",
+ ) // v1
+ .id("upload")
+ .add_with((
+ "serviceAccountJson",
+ "${{ steps.auth.outputs.credentials_file_path }}",
+ ))
+ .add_with(("packageName", "com.macro.workspace.mobile"))
+ .add_with(("releaseFiles", "${{ steps.artifact.outputs.bundle }}"))
+ .add_with(("mappingFile", "${{ steps.artifact.outputs.mapping }}"))
+ .add_with(("releaseName", "${{ needs.check.outputs.release_name }}"))
+ .add_with(("track", "internal"))
+ .add_with(("status", "completed"))
+ .add_with(("whatsNewDirectory", "${{ runner.temp }}/whatsnew"))
+}
+
+/// Set before the promotion starts, so a drift check running meanwhile
+/// treats the version code as possibly promoted.
+fn mark_promotion_pending() -> Step<Run> {
+ Step::new("Mark the promotion as started")
+ .run(concat!(
+ include_str!("scripts/android_play_statuses.sh"),
+ indoc::indoc! {r#"
+ set -euo pipefail
+ set_commit_status "$BUILT_SHA" android-play/release pending \
+ "$(android_release_description "$VERSION_CODE" "$NATIVE_HASH")"
+ "#}
+ ))
+ .id("pending")
+ .shell("bash")
+ .add_env(("NATIVE_HASH", "${{ steps.stamp.outputs.native_hash }}"))
+}
+
+/// Internal → production, full rollout. Play can take a moment to show the
+/// internal release in a fresh edit, so the promotion is retried briefly.
+fn promote_production() -> Step<Run> {
+ steps::logged_run(
+ "Promote to production",
+ indoc::indoc! {r#"
+ set -euo pipefail
+ for attempt in 1 2 3 4 5; do
+ if node scripts/android-play-promote.mjs; then
+ exit 0
+ fi
+ echo "Promotion attempt ${attempt} failed; retrying in 30s."
+ sleep 30
+ done
+ echo "Could not promote version code ${VERSION_CODE} to production; promote it by hand with publish-android-play.yml (operation=promote-production)." >&2
+ exit 1
+ "#},
+ )
+ .id("promote")
+ .working_directory(xtask_paths::repo_dir!("apps/web"))
+ .add_env(("GOOGLE_PLAY_ACCESS_TOKEN", "${{ steps.auth.outputs.access_token }}"))
+ .add_env(("CHANGES_NOT_SENT_FOR_REVIEW", "false"))
+}
+
+/// Success, or failure for a promotion that failed or was cancelled midway
+/// (the drift check treats failure as "may be promoted").
+fn mark_promotion_result() -> Step<Run> {
+ Step::new("Record the promotion result")
+ .run(concat!(
+ include_str!("scripts/android_play_statuses.sh"),
+ indoc::indoc! {r#"
+ set -euo pipefail
+ state=failure
+ if [[ "$PROMOTE_OUTCOME" == success ]]; then
+ state=success
+ fi
+ set_commit_status "$BUILT_SHA" android-play/release "$state" \
+ "$(android_release_description "$VERSION_CODE" "$NATIVE_HASH")"
+ "#}
+ ))
+ .if_condition(Expression::new(
+ "always() && steps.pending.outcome == 'success'",
+ ))
+ .shell("bash")
+ .add_env(("NATIVE_HASH", "${{ steps.stamp.outputs.native_hash }}"))
+ .add_env(("PROMOTE_OUTCOME", "${{ steps.promote.outcome }}"))
+}
+
+fn pr_comment() -> Step<Use> {
+ Step::new("Comment on the PR")
+ .uses(
+ "actions",
+ "github-script",
+ "f28e40c7f34bde8b3046d885e986cb6290c5673b",
+ )
+ .if_condition(Expression::new("success() || failure()"))
+ .add_with(("github-token", "${{ secrets.GITHUB_TOKEN }}"))
+ .add_env(("JOB_NAME", PUBLISH_JOB_NAME))
+ .add_env(("BUILD_URL", "${{ github.event.workflow_run.html_url }}"))
+ .add_env(("RELEASE_NAME", "${{ needs.check.outputs.release_name }}"))
+ .add_env(("JOB_STATUS", "${{ job.status }}"))
+ .add_env(("UPLOAD_OUTCOME", "${{ steps.upload.outcome }}"))
+ .add_with((
+ "script",
+ include_str!("scripts/android_play_publish_comment.js"),
+ ))
+}
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/android_play_publish/test.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/android_play_publish/test.rs
new file mode 100644
index 0000000000..af7f8255ad
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/android_play_publish/test.rs
@@ -0,0 +1,391 @@
+use super::*;
+use crate::workflows::{android_play_release, android_release_drift, web_app_check_main};
+
+/// Run `script` under bash after `fakes`, with `env`, returning the exit
+/// status, stdout + stderr, and what the script wrote to `$GITHUB_OUTPUT`.
+fn run(fakes: &str, script: &str, env: &[(&str, &str)]) -> (bool, String, String) {
+ let outputs = tempfile::NamedTempFile::new().expect("step outputs");
+ let output = std::process::Command::new("bash")
+ .arg("-c")
+ .arg(format!("{fakes}\n{script}"))
+ .env_remove("BASH_ENV")
+ .env("GITHUB_OUTPUT", outputs.path())
+ .env("GH_REPO", "example/repo")
+ .envs(env.iter().copied())
+ .output()
+ .expect("run script");
+ let log = format!(
+ "{}{}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let outputs = std::fs::read_to_string(outputs.path()).expect("read step outputs");
+ (output.status.success(), log, outputs)
+}
+
+fn output<'a>(outputs: &'a str, key: &str) -> Option<&'a str> {
+ outputs
+ .lines()
+ .find_map(|line| line.strip_prefix(&format!("{key}=")))
+}
+
+const VERIFY_FAKES: &str = r#"
+gh() {
+ case "$*" in
+ "api repos/example/repo/actions/runs/7/attempts/1/jobs "*) echo "$FAKE_BUILD" ;;
+ "pr list --repo example/repo --head feature --base main --state open "*) echo "$FAKE_PR" ;;
+ "pr view 5 --repo example/repo --json labels "*) echo "$FAKE_LABELED" ;;
+ "api --paginate repos/example/repo/issues/5/events "*) [[ -z "$FAKE_EVENTS" ]] || printf '%s\n' "$FAKE_EVENTS" ;;
+ "api repos/example/repo/collaborators/alice/permission "*) echo "$FAKE_PERMISSION" ;;
+ *) echo "unexpected: gh $*" >&2; return 1 ;;
+ esac
+}
+gh_fetch() { [[ "$1" == "$HEAD_SHA" ]]; }
+bun() { [[ "$*" == "scripts/android-native.mjs version-code $HEAD_SHA" ]] && echo 22; }
+git() { [[ "$1 $2" == "show ${HEAD_SHA}:apps/web/tauri/src-tauri/tauri.android.conf.json" ]] && echo '{"version":"2.0.1"}'; }
+"#;
+
+/// What the publisher's check should make of a build run.
+#[derive(Clone, Copy, PartialEq, Debug)]
+enum Expect {
+ Publish,
+ /// Nothing to publish: end quietly.
+ Skip,
+ /// Fail, saying why.
+ Refuse,
+}
+
+/// A scenario: its name, the environment it overrides, the expected outcome.
+type Case<'a> = (&'a str, &'a [(&'a str, &'a str)], Expect);
+
+const LABELED_BY_ALICE: &str =
+ r#"{"event":"labeled","login":"alice","type":"User","at":"2026-11-03T10:00:00Z"}"#;
+
+/// The publisher's `check` job: only a successful build that a person with
+/// write access started by adding `android-update` is published.
+#[test]
+fn publishes_only_a_build_the_label_started() {
+ let script = include_str!("../scripts/android_play_publish_verify.sh");
+ let unlabeled = format!(
+ "{LABELED_BY_ALICE}\n{}",
+ r#"{"event":"unlabeled","login":"alice","type":"User","at":"2026-11-03T10:01:00Z"}"#
+ );
+ let bob_later = format!(
+ "{LABELED_BY_ALICE}\n{}",
+ r#"{"event":"labeled","login":"bob","type":"User","at":"2026-11-03T10:02:00Z"}"#
+ );
+ let bot = r#"{"event":"labeled","login":"alice","type":"Bot","at":"2026-11-03T10:00:00Z"}"#;
+ let cases: &[Case] = &[
+ ("labeled by a writer", &[], Expect::Publish),
+ (
+ "another workflow file",
+ &[("RUN_PATH", ".github/workflows/other.yml")],
+ Expect::Skip,
+ ),
+ (
+ "release job skipped",
+ &[("FAKE_BUILD", "skipped")],
+ Expect::Skip,
+ ),
+ ("no open PR", &[("FAKE_PR", "")], Expect::Refuse),
+ ("label gone", &[("FAKE_LABELED", "false")], Expect::Refuse),
+ (
+ "label last removed",
+ &[("FAKE_EVENTS", &unlabeled)],
+ Expect::Refuse,
+ ),
+ ("no label events", &[("FAKE_EVENTS", "")], Expect::Refuse),
+ ("added by a bot", &[("FAKE_EVENTS", bot)], Expect::Refuse),
+ (
+ "someone else added it since",
+ &[("FAKE_EVENTS", &bob_later)],
+ Expect::Refuse,
+ ),
+ (
+ "started by someone else",
+ &[("RUN_ACTOR", "mallory")],
+ Expect::Refuse,
+ ),
+ (
+ "read access only",
+ &[("FAKE_PERMISSION", "read")],
+ Expect::Refuse,
+ ),
+ (
+ "run created by a later push",
+ &[("RUN_CREATED_AT", "2026-11-03T10:20:00Z")],
+ Expect::Refuse,
+ ),
+ (
+ "run created before the label",
+ &[("RUN_CREATED_AT", "2026-11-03T09:55:00Z")],
+ Expect::Refuse,
+ ),
+ ];
+ for (case, overrides, expected) in cases {
+ let mut env = vec![
+ ("RUN_ID", "7"),
+ ("RUN_ATTEMPT", "1"),
+ ("RUN_PATH", ".github/workflows/android-play-release.yml"),
+ ("RUN_ACTOR", "alice"),
+ ("RUN_CREATED_AT", "2026-11-03T10:00:04Z"),
+ ("HEAD_SHA", "abc123"),
+ ("HEAD_BRANCH", "feature"),
+ ("FAKE_BUILD", "success"),
+ ("FAKE_PR", "5"),
+ ("FAKE_LABELED", "true"),
+ ("FAKE_EVENTS", LABELED_BY_ALICE),
+ ("FAKE_PERMISSION", "write"),
+ ];
+ for &(key, value) in overrides.iter() {
+ env.retain(|&(k, _)| k != key);
+ env.push((key, value));
+ }
+ let (ok, log, outputs) = run(VERIFY_FAKES, script, &env);
+ if *expected == Expect::Refuse {
+ assert!(!ok, "{case} must be refused: {log}");
+ assert!(log.contains("Not publishing run 7: "), "{case}: {log}");
+ assert_eq!(output(&outputs, "publish"), None, "{case}: {outputs}");
+ continue;
+ }
+ assert!(ok, "{case}: {log}");
+ let publish = *expected == Expect::Publish;
+ assert_eq!(
+ output(&outputs, "publish"),
+ Some(if publish { "true" } else { "false" }),
+ "{case}: {outputs}"
+ );
+ if publish {
+ assert_eq!(output(&outputs, "pr_number"), Some("5"));
+ assert_eq!(output(&outputs, "version_code"), Some("22"));
+ assert_eq!(output(&outputs, "release_name"), Some("2.0.1 (22)"));
+ }
+ }
+}
+
+const HASH: &str = "1c42afd83e761d9bd933b645bbd239e817b4462e";
+
+/// The merge gate finds the watcher's `android-play/live` status on any of
+/// the PR's commits, but only for this version code, merge-result native
+/// hash and PR.
+#[test]
+fn gate_requires_a_matching_live_status() {
+ let script = concat!(
+ include_str!("../scripts/android_play_statuses.sh"),
+ include_str!("../scripts/android_native_check_live.sh")
+ );
+ let fakes = r#"
+pr_merge_commit() { echo merge; }
+gh_fetch() { [[ "$1" == merge ]]; }
+bun() { [[ "$*" == "scripts/android-native.mjs hash merge" ]] && echo "$FAKE_HASH"; }
+gh() {
+ [[ "$1 $2" == "api graphql" && "$*" == *"context=android-play/live"* && "$*" == *"pr=5"* ]] || return 1
+ [[ -z "$FAKE_STATUSES" ]] || printf '%s\n' "$FAKE_STATUSES"
+}
+"#;
+ let live = |code: &str, hash: &str, pr: &str| {
+ format!("Version code {code} is live on Google Play (native tree {hash}, PR #{pr})")
+ };
+ let other_hash = "0000000000000000000000000000000000000000";
+ let cases = [
+ (
+ "live on an older commit",
+ format!("old success {}\nhead pending x", live("22", HASH, "5")),
+ true,
+ ),
+ ("no statuses", String::new(), false),
+ (
+ "still pending",
+ format!("head pending {}", live("22", HASH, "5")),
+ false,
+ ),
+ (
+ "other native tree",
+ format!("head success {}", live("22", other_hash, "5")),
+ false,
+ ),
+ (
+ "other version code",
+ format!("head success {}", live("2", HASH, "5")),
+ false,
+ ),
+ (
+ "other PR",
+ format!("head success {}", live("22", HASH, "6")),
+ false,
+ ),
+ ];
+ for (case, statuses, pass) in cases {
+ let (ok, log, _) = run(
+ fakes,
+ script,
+ &[
+ ("PR_NUMBER", "5"),
+ ("VERSION_CODE", "22"),
+ ("FAKE_HASH", HASH),
+ ("FAKE_STATUSES", &statuses),
+ ],
+ );
+ assert_eq!(ok, pass, "{case}: {log}");
+ }
+}
+
+/// Drift reads whether the publisher submitted the stale version code:
+/// success is promoted, pending or failure unknown, nothing not promoted.
+#[test]
+fn drift_reads_the_promotion_from_the_release_status() {
+ let script = concat!(
+ include_str!("../scripts/android_play_statuses.sh"),
+ include_str!("../scripts/android_release_drift_promoted.sh")
+ );
+ let fakes = r#"
+gh() {
+ case "$*" in
+ "run list --repo example/repo --workflow android-play-publish.yml "*) [[ "$FAKE_RUNS" != fail ]] && echo "$FAKE_RUNS" ;;
+ "api repos/example/repo/commits/before/status "*) [[ -z "$FAKE_BEFORE" ]] || printf '%s\n' "$FAKE_BEFORE" ;;
+ "api graphql "*) [[ -z "$FAKE_PR_STATUSES" ]] || printf '%s\n' "$FAKE_PR_STATUSES" ;;
+ *) echo "unexpected: gh $*" >&2; return 1 ;;
+ esac
+}
+"#;
+ let release = |code: &str| format!("Version code {code} (native tree {HASH})");
+ let cases = [
+ (
+ "submitted from the old head",
+ "0",
+ format!("success {}", release("20")),
+ String::new(),
+ Some("true"),
+ ),
+ (
+ "submitted from an earlier commit",
+ "0",
+ String::new(),
+ format!("c1 success {}", release("20")),
+ Some("true"),
+ ),
+ (
+ "promotion under way",
+ "0",
+ format!("pending {}", release("20")),
+ String::new(),
+ None,
+ ),
+ (
+ "promotion failed midway",
+ "0",
+ String::new(),
+ format!("c1 failure {}", release("20")),
+ None,
+ ),
+ (
+ "another version code",
+ "0",
+ format!("success {}", release("21")),
+ String::new(),
+ Some("false"),
+ ),
+ (
+ "a code with the same prefix",
+ "0",
+ format!("success {}", release("200")),
+ String::new(),
+ Some("false"),
+ ),
+ (
+ "never published",
+ "0",
+ String::new(),
+ String::new(),
+ Some("false"),
+ ),
+ (
+ "runs unreadable",
+ "fail",
+ String::new(),
+ String::new(),
+ None,
+ ),
+ ];
+ for (case, runs, before, pr_statuses, promoted) in cases {
+ let (ok, log, outputs) = run(
+ fakes,
+ script,
+ &[
+ ("PR_NUMBER", "5"),
+ ("BEFORE_SHA", "before"),
+ ("VERSION_CODE", "20"),
+ ("FAKE_RUNS", runs),
+ ("FAKE_BEFORE", &before),
+ ("FAKE_PR_STATUSES", &pr_statuses),
+ ],
+ );
+ assert!(ok, "{case}: the lookup never fails the drift job: {log}");
+ assert_eq!(output(&outputs, "promoted"), promoted, "{case}: {log}");
+ }
+}
+
+/// Google's identity provider admits only main-copy workflows; a PR-side
+/// workflow must not even try to sign in to Play.
+#[test]
+fn only_main_copy_workflows_sign_in_to_play() {
+ for (name, yaml) in [
+ (
+ "android-play-release",
+ android_play_release::android_play_release(),
+ ),
+ (
+ "android-release-drift",
+ android_release_drift::android_release_drift(),
+ ),
+ (
+ "web-app-check-main",
+ web_app_check_main::web_app_check_main(),
+ ),
+ ] {
+ let yaml = yaml.to_string().expect("workflow YAML");
+ assert!(
+ !yaml.contains("google-github-actions/auth") && !yaml.contains("GOOGLE_PLAY_"),
+ "{name} runs PR code and must not sign in to Play"
+ );
+ }
+ let yaml = android_play_publish().to_string().expect("workflow YAML");
+ let workflow: serde_yaml::Value = serde_yaml::from_str(&yaml).expect("parsed workflow");
+ let on = workflow["on"].as_mapping().expect("triggers");
+ assert_eq!(on.len(), 1, "workflow_run only: {yaml}");
+ assert!(on.contains_key("workflow_run"));
+ assert!(
+ workflow["jobs"]["check"]["permissions"]["id-token"].is_null(),
+ "the check job needs no Play identity"
+ );
+ assert_eq!(
+ workflow["jobs"]["publish"]["if"].as_str(),
+ Some("needs.check.outputs.publish == 'true'")
+ );
+ let steps: Vec<&str> = workflow["jobs"]["publish"]["steps"]
+ .as_sequence()
+ .expect("publish steps")
+ .iter()
+ .filter_map(|step| step["name"].as_str())
+ .collect();
+ let at = |name: &str| {
+ steps
+ .iter()
+ .position(|step| *step == name)
+ .unwrap_or_else(|| panic!("missing step {name}: {steps:?}"))
+ };
+ assert!(
+ at("Require the PR's Android native code to be unchanged since the build")
+ < at("Upload to internal testing")
+ );
+ assert!(at("Write the provenance stamp as release notes") < at("Upload to internal testing"));
+ assert!(
+ at("Upload to internal testing")
+ < at("Require the native code to be unchanged before promoting")
+ );
+ assert!(
+ at("Require the native code to be unchanged before promoting")
+ < at("Mark the promotion as started")
+ );
+ assert!(at("Mark the promotion as started") < at("Promote to production"));
+}
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/android_play_release.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/android_play_release.rs
index 7610cc14ab..81c69d38e5 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/android_play_release.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/android_play_release.rs
@@ -1,28 +1,28 @@
//! `Android Play Release` — add the `android-update` label to a PR with
//! Android native changes and this workflow builds the signed App Bundle
-//! from the PR head, uploads it to Google Play's internal track and promotes
-//! it to production (full rollout; Google review applies) — the release the
+//! from the PR head and keeps it as the `android-release` workflow artifact.
+//! When it succeeds, [`super::android_play_publish`] (which runs `main`'s
+//! copy) uploads it to Google Play's internal track and promotes it to
+//! production (full rollout; Google review applies) — the release the
//! `Android Native Check` merge gate (a job of [`super::web_app_check_main`])
//! then waits on; [`super::android_release_watch`] re-runs the gate once the
//! release is live. The iOS counterpart is [`super::ios_app_store_release`].
//!
+//! This workflow runs the PR's code, so it gets no Play access: only the
+//! publisher can sign in to Play.
+//!
//! The PR must already contain the version code bump (`just android-bump`
//! in `apps/web`, committed): the preconditions verify it against the base
//! branch and fail fast otherwise. Release retries are label-driven (remove
//! and re-add `android-update`).
//!
//! Play is the only artifact store that matters: the bundle and its R8
-//! mapping are also kept as a workflow artifact, but nothing ties releases to
-//! production release tags any more (the former tag-driven
-//! `release-android.yml` is gone). Each upload carries a provenance stamp in
-//! its release notes — the Android native hash it was built from and the PR
-//! number — that the gate and the watcher compare against the PR's merge
-//! result, exactly like the iOS TestFlight stamp.
+//! mapping are also kept as a workflow artifact (90 days), but nothing ties
+//! releases to production release tags any more (the former tag-driven
+//! `release-android.yml` is gone).
//!
//! Credentials: the signing keystore and Firebase config come from Doppler
-//! (`android-release/prd` via `ANDROID_RELEASE_DOPPLER_TOKEN`); Play access is
-//! keyless (Workload Identity Federation through the repository variables
-//! `GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER` / `GOOGLE_PLAY_SERVICE_ACCOUNT`).
+//! (`android-release/prd` via `ANDROID_RELEASE_DOPPLER_TOKEN`).
use gh_workflow::{
Concurrency, Event, Expression, Job, Level, Permissions, PullRequest, PullRequestType, Run,
@@ -61,7 +61,6 @@ fn release_job() -> Job {
.actions(Level::Read)
.checks(Level::Read)
.contents(Level::Read)
- .id_token(Level::Write)
.pull_requests(Level::Write)
.statuses(Level::Read),
)
@@ -81,11 +80,7 @@ fn release_job() -> Job {
.add_step(preserve_build_log())
.add_step(verify_and_collect())
.add_step(head_guard())
- .add_step(provenance_stamp())
.add_step(upload_workflow_artifact())
- .add_step(play_auth())
- .add_step(upload_internal())
- .add_step(promote_production())
.add_step(remove_signing_material())
.add_step(pr_comment())
}
@@ -104,13 +99,7 @@ fn checkout_pr_head() -> Step<Use> {
/// Bun before Nix: the preconditions run the Android scripts before the
/// toolchain is set up.
fn setup_bun() -> Step<Use> {
- Step::new("Setup Bun")
- .uses(
- "oven-sh",
- "setup-bun",
- "0c5077e51419868618aeaa5fe8019c62421857d6",
- ) // v2.2.0
- .add_with(("bun-version", "1.3.13"))
+ steps::setup_bun_pinned()
}
/// `android-update` means "release this and merge it when it is live", so the
@@ -280,22 +269,6 @@ fn head_guard() -> Step<Run> {
.working_directory(xtask_paths::repo_dir!("apps/web"))
}
-/// The release notes carry the native hash and PR number, which the gate and
-/// the watcher compare against the merge result (the TestFlight stamp's twin).
-fn provenance_stamp() -> Step<Run> {
- steps::logged_run(
- "Write the provenance stamp as release notes",
- indoc::indoc! {r#"
- set -euo pipefail
- hash=$(bun scripts/android-native.mjs hash HEAD)
- mkdir -p "$RUNNER_TEMP/whatsnew"
- printf 'native tree %s for PR #%s\n' "$hash" "$PR_NUMBER" > "$RUNNER_TEMP/whatsnew/whatsnew-en-US"
- echo "Stamp: native tree ${hash} for PR #${PR_NUMBER}"
- "#},
- )
- .working_directory(xtask_paths::repo_dir!("apps/web"))
-}
-
fn upload_workflow_artifact() -> Step<Use> {
Step::new("Upload verified Android artifact")
.uses(
@@ -309,78 +282,11 @@ fn upload_workflow_artifact() -> Step<Use> {
.add_with(("retention-days", 90))
}
-/// Keyless Play access: a credentials file for the upload action and an
-/// access token for the promotion script.
-fn play_auth() -> Step<Use> {
- Step::new("Authenticate to Google Play")
- .uses(
- "google-github-actions",
- "auth",
- "7c6bc770dae815cd3e89ee6cdf493a5fab2cc093",
- ) // v3
- .id("auth")
- .add_with((
- "workload_identity_provider",
- "${{ vars.GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER }}",
- ))
- .add_with(("service_account", "${{ vars.GOOGLE_PLAY_SERVICE_ACCOUNT }}"))
- .add_with(("token_format", "access_token"))
- .add_with((
- "access_token_scopes",
- "https://www.googleapis.com/auth/androidpublisher",
- ))
- .add_with(("export_environment_variables", false))
-}
-
-fn upload_internal() -> Step<Use> {
- Step::new("Upload to internal testing")
- .uses(
- "r0adkll",
- "upload-google-play",
- "e738b9dd8f2476ea806d921b64aacd24f34515a5",
- ) // v1
- .add_with((
- "serviceAccountJson",
- "${{ steps.auth.outputs.credentials_file_path }}",
- ))
- .add_with(("packageName", "com.macro.workspace.mobile"))
- .add_with(("releaseFiles", "${{ steps.artifact.outputs.bundle }}"))
- .add_with(("mappingFile", "${{ steps.artifact.outputs.mapping }}"))
- .add_with(("releaseName", "${{ steps.metadata.outputs.release_name }}"))
- .add_with(("track", "internal"))
- .add_with(("status", "completed"))
- .add_with(("whatsNewDirectory", "${{ runner.temp }}/whatsnew"))
-}
-
-/// Internal → production, full rollout. Play can take a moment to show the
-/// internal release in a fresh edit, so the promotion is retried briefly.
-fn promote_production() -> Step<Run> {
- steps::logged_run(
- "Promote to production",
- indoc::indoc! {r#"
- set -euo pipefail
- for attempt in 1 2 3 4 5; do
- if node scripts/android-play-promote.mjs; then
- exit 0
- fi
- echo "Promotion attempt ${attempt} failed; retrying in 30s."
- sleep 30
- done
- echo "Could not promote version code ${VERSION_CODE} to production; promote it by hand with publish-android-play.yml (operation=promote-production)." >&2
- exit 1
- "#},
- )
- .working_directory(xtask_paths::repo_dir!("apps/web"))
- .add_env(("GOOGLE_PLAY_ACCESS_TOKEN", "${{ steps.auth.outputs.access_token }}"))
- .add_env(("VERSION_CODE", "${{ steps.preconditions.outputs.version_code }}"))
- .add_env(("CHANGES_NOT_SENT_FOR_REVIEW", "false"))
-}
-
fn remove_signing_material() -> Step<Run> {
Step::new("Remove signing material")
.run(indoc::indoc! {r#"
rm -rf "$RUNNER_TEMP/android-signing" "$RUNNER_TEMP/android-release.json" \
- "$RUNNER_TEMP/android-google-services.json" "$RUNNER_TEMP/whatsnew" || true
+ "$RUNNER_TEMP/android-google-services.json" || true
rm -f apps/web/tauri/src-tauri/gen/android/keystore.properties || true
"#})
.if_condition(Expression::new("always()"))
@@ -394,9 +300,11 @@ fn pr_comment() -> Step<Use> {
"github-script",
"f28e40c7f34bde8b3046d885e986cb6290c5673b",
)
- // Not `always()`: a run the drift workflow cancelled must not post
- // "failed, re-add the label" next to drift's own comment.
- .if_condition(Expression::new("success() || failure()"))
+ // Failures only: Android Play Publish comments the outcome of a
+ // successful build. Not `always()` either: a run the drift workflow
+ // cancelled must not post "failed, re-add the label" next to drift's
+ // own comment.
+ .if_condition(Expression::new("failure()"))
.add_with(("github-token", "${{ secrets.GITHUB_TOKEN }}"))
.add_with((
"script",
@@ -408,55 +316,39 @@ fn pr_comment() -> Step<Use> {
const runUrl =
`${context.serverUrl}/${context.repo.owner}/${context.repo.repo}` +
`/actions/runs/${context.runId}`;
- const success = '${{ job.status }}' === 'success';
- const SUCCESS_BODY = [
- `🤖 Android ${releaseName} was uploaded to Google Play internal testing and submitted for a full production rollout.`,
- '',
- 'When Google approves it, the version goes live, the **Android Release Watch** workflow',
- 're-runs the **Android Native Check** on this PR within half an hour of that, and the PR',
- 'becomes mergeable. To merge it the moment that happens, click **Enable auto-merge** on this PR now (squash).',
- 'After merge, the next prod deploy applies the Android native build floor committed in `min-native-build.json`.',
- '',
- `[Workflow run](${runUrl})`,
- ].join('\n');
- let body;
- if (success) {
- body = SUCCESS_BODY;
- } else {
- // Name the failed step and, when it is one that logs its
- // output (steps::logged_run), quote the end of that output.
- let failedStep = null;
+ // Name the failed step and, when it is one that logs its
+ // output (steps::logged_run), quote the end of that output.
+ let failedStep = null;
+ try {
+ const { data } = await github.rest.actions.listJobsForWorkflowRunAttempt({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ run_id: context.runId,
+ attempt_number: Number(process.env.GITHUB_RUN_ATTEMPT),
+ });
+ const job = data.jobs.find((j) => j.name === 'Android Play Release');
+ failedStep = job?.steps.find((s) => s.conclusion === 'failure')?.name ?? null;
+ } catch (error) {
+ core.warning(`Could not list this job's steps: ${error.message}`);
+ }
+ const read = (file) => {
try {
- const { data } = await github.rest.actions.listJobsForWorkflowRunAttempt({
- owner: context.repo.owner,
- repo: context.repo.repo,
- run_id: context.runId,
- attempt_number: Number(process.env.GITHUB_RUN_ATTEMPT),
- });
- const job = data.jobs.find((j) => j.name === 'Android Play Release');
- failedStep = job?.steps.find((s) => s.conclusion === 'failure')?.name ?? null;
- } catch (error) {
- core.warning(`Could not list this job's steps: ${error.message}`);
- }
- const read = (file) => {
- try {
- return fs.readFileSync(path.join(process.env.RUNNER_TEMP, file), 'utf8');
- } catch {
- return '';
- }
- };
- let tail = '';
- if (failedStep && read('last-step.name').trim() === failedStep) {
- const lines = read('last-step.log').replace(/\x1b\[[0-9;]*m/g, '').trimEnd().split('\n');
- tail = lines.slice(-30).join('\n').slice(-3000);
+ return fs.readFileSync(path.join(process.env.RUNNER_TEMP, file), 'utf8');
+ } catch {
+ return '';
}
- body = [
- `🤖 Android Play release for ${releaseName} **failed**${failedStep ? ` at **${failedStep}**` : ''} — see the [workflow run](${runUrl}).`,
- ...(tail ? ['', '```text', tail, '```'] : []),
- '',
- 'Fix the problem, then remove and re-add the `android-update` label to retry.',
- ].join('\n');
+ };
+ let tail = '';
+ if (failedStep && read('last-step.name').trim() === failedStep) {
+ const lines = read('last-step.log').replace(/\x1b\[[0-9;]*m/g, '').trimEnd().split('\n');
+ tail = lines.slice(-30).join('\n').slice(-3000);
}
+ const body = [
+ `🤖 Android Play release for ${releaseName} **failed**${failedStep ? ` at **${failedStep}**` : ''} — see the [workflow run](${runUrl}).`,
+ ...(tail ? ['', '```text', tail, '```'] : []),
+ '',
+ 'Fix the problem, then remove and re-add the `android-update` label to retry.',
+ ].join('\n');
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/android_release_drift.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/android_release_drift.rs
index 6d8e0a8a30..6d3f8975cd 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/android_release_drift.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/android_release_drift.rs
@@ -12,9 +12,13 @@
//!
//! Unlike App Store review, a Play production release cannot be withdrawn
//! once submitted: if the stale bundle was already promoted, the comment
-//! says so loudly and the follow-up should ship as soon as possible. The
+//! says so loudly and the follow-up should ship as soon as possible. This
+//! job runs the PR's code, so it cannot ask Play; it reads the
+//! `android-play/release` commit status [`super::android_play_publish`] sets
+//! around the promotion, after waiting for publish runs in progress. The
//! production status remains unknown when the prior native tree cannot be
-//! verified, authentication fails, or the Play lookup fails.
+//! verified, a promotion may have happened (pending or failed), or the
+//! lookup fails.
//! The iOS counterpart is [`super::ios_release_drift`].
use gh_workflow::{
@@ -45,13 +49,15 @@ fn drift_job() -> Job {
github.event.pull_request.head.repo.full_name == github.repository",
))
.runs_on(runners::Runner::TinyNoCache.to_string())
- .timeout_minutes(15u32)
+ // Cancelling release runs waits up to 3 minutes, publish runs in
+ // progress up to 10.
+ .timeout_minutes(20u32)
.permissions(
Permissions::default()
.actions(Level::Write)
.contents(Level::Read)
- .id_token(Level::Write)
- .pull_requests(Level::Write),
+ .pull_requests(Level::Write)
+ .statuses(Level::Read),
)
.add_env(("GH_TOKEN", "${{ github.token }}"))
.add_env(("GH_REPO", "${{ github.repository }}"))
@@ -60,7 +66,6 @@ fn drift_job() -> Job {
.add_step(setup_bun())
.add_step(detect())
.add_step(cancel_release_runs())
- .add_step(play_auth())
.add_step(play_status())
.add_step(remove_label())
.add_step(comment())
@@ -71,13 +76,7 @@ fn changed() -> Expression {
}
fn setup_bun() -> Step<Use> {
- Step::new("Setup Bun")
- .uses(
- "oven-sh",
- "setup-bun",
- "0c5077e51419868618aeaa5fe8019c62421857d6",
- ) // v2.2.0
- .add_with(("bun-version", "1.3.13"))
+ steps::setup_bun_pinned()
}
fn detect() -> Step<Run> {
@@ -124,53 +123,24 @@ fn cancel_release_runs() -> Step<Run> {
.add_env(("HEAD_REF", "${{ github.event.pull_request.head.ref }}"))
}
-fn play_auth() -> Step<Use> {
- Step::new("Authenticate to Google Play")
- .uses(
- "google-github-actions",
- "auth",
- "7c6bc770dae815cd3e89ee6cdf493a5fab2cc093",
- ) // v3
- .id("auth")
- .if_condition(Expression::new(format!(
- "{CHANGED} && steps.detect.outputs.version_code != ''"
- )))
- .add_with((
- "workload_identity_provider",
- "${{ vars.GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER }}",
- ))
- .add_with(("service_account", "${{ vars.GOOGLE_PLAY_SERVICE_ACCOUNT }}"))
- .add_with(("token_format", "access_token"))
- .add_with((
- "access_token_scopes",
- "https://www.googleapis.com/auth/androidpublisher",
- ))
- .add_with(("create_credentials_file", false))
- .add_with(("export_environment_variables", false))
-}
-
/// Was the stale bundle already promoted to production (in review or
/// published)? Nothing can withdraw it then.
fn play_status() -> Step<Run> {
- Step::new("Check whether the stale version code is already on Play")
- .run(indoc::indoc! {r#"
- set -euo pipefail
- bun scripts/android-play-status.mjs --version-code "$VERSION_CODE" || true
- "#})
+ Step::new("Check whether the stale version code was submitted to production")
+ .run(concat!(
+ include_str!("scripts/android_play_statuses.sh"),
+ include_str!("scripts/android_release_drift_promoted.sh")
+ ))
.id("status")
.if_condition(Expression::new(format!(
"{CHANGED} && steps.detect.outputs.version_code != ''"
)))
.shell("bash")
- .working_directory(xtask_paths::repo_dir!("apps/web"))
+ .add_env(("BEFORE_SHA", "${{ github.event.before }}"))
.add_env(("VERSION_CODE", "${{ steps.detect.outputs.version_code }}"))
- .add_env((
- "GOOGLE_PLAY_ACCESS_TOKEN",
- "${{ steps.auth.outputs.access_token }}",
- ))
}
-/// `always()`: even if the Play check failed, the label must come off and
+/// `always()`: even if the status check failed, the label must come off and
/// someone must be told.
fn after_detect() -> Expression {
Expression::new(format!("always() && {CHANGED}"))
@@ -191,9 +161,9 @@ fn comment() -> Step<Run> {
if [[ "$PROMOTED" == "true" ]]; then
body="🚨 Android native changes were pushed to this PR after version code ${VERSION_CODE} had already been promoted to Google Play production, so that bundle is (or is about to be) live with native code this PR no longer matches. A Play release cannot be withdrawn: bump (\`${bump}\`), commit, re-add the \`android-update\` label, and ship the follow-up as soon as possible. The label was removed."
elif [[ "$PROMOTED" == "false" ]]; then
- body="🤖 Android native code changed after this PR's Play release started. Google Play reports that version code ${VERSION_CODE} has not been promoted to production. The \`android-update\` label was removed; any bundle on the internal track remains there for testers. Once in-progress release runs have stopped and the PR is ready again, bump (\`${bump}\`), commit, push, and re-add \`android-update\`."
+ body="🤖 Android native code changed after this PR's Play release started. Android Play Publish did not submit version code ${VERSION_CODE} to production. The \`android-update\` label was removed; any bundle on the internal track remains there for testers. Once in-progress release runs have stopped and the PR is ready again, bump (\`${bump}\`), commit, push, and re-add \`android-update\`."
else
- body="⚠️ Android native code changed or could not be compared with this PR's prior release, and Google Play production status could not be verified. The prior bundle may already be in review or live. The \`android-update\` label was removed. Keep the reviewed-SHA authentication restriction and verify production status in Play Console or through a check from an approved revision. Treat the prior release as potentially live until verified."
+ body="⚠️ Android native code changed or could not be compared with this PR's prior release, and whether that release was submitted to Google Play production could not be determined. The prior bundle may already be in review or live. The \`android-update\` label was removed. Check the production track in Play Console, and treat the prior release as potentially live until you have."
fi
gh pr comment "$PR_NUMBER" --repo "$GH_REPO" --body "$body"
"#})
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/android_release_watch.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/android_release_watch.rs
index dabe385e31..f8c0ac5b22 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/android_release_watch.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/android_release_watch.rs
@@ -6,8 +6,12 @@
//! `android-update` (the label that started the
//! [`super::android_play_release`] run), asks Play whether the version code
//! committed at the PR head is live (built from the native code of the PR's
-//! merge result, like the gate checks), and when it is, re-runs the PR's
-//! failed `Android Native Check` job so the gate turns green on its own.
+//! merge result, like the gate checks), and when it is, marks the PR head
+//! with the `android-play/live` commit status — the gate runs the PR's code,
+//! so it cannot ask Play itself and reads this status instead — and re-runs
+//! the PR's failed `Android Native Check` job so the gate turns green on its
+//! own. Running from `main` on a schedule, it is one of the few workflows
+//! Google's identity provider admits.
//! Re-running an existing job is how this stays within GitHub's rule that
//! events created with the workflow token never start workflows. The iOS
//! counterpart is [`super::ios_release_watch`].
@@ -32,7 +36,8 @@ pub fn android_release_watch() -> Workflow {
.actions(Level::Write)
.contents(Level::Read)
.id_token(Level::Write)
- .pull_requests(Level::Write),
+ .pull_requests(Level::Write)
+ .statuses(Level::Write),
)
.add_job("watch", watch_job())
}
@@ -47,7 +52,7 @@ fn watch_job() -> Job {
.add_step(find_prs())
.add_step(steps::checkout(false, false).if_condition(gated()))
.add_step(setup_bun())
- .add_step(play_auth())
+ .add_step(steps::google_play_auth(false).if_condition(gated()))
.add_step(rerun_live_checks())
}
@@ -72,43 +77,14 @@ fn find_prs() -> Step<Run> {
}
fn setup_bun() -> Step<Use> {
- Step::new("Setup Bun")
- .uses(
- "oven-sh",
- "setup-bun",
- "0c5077e51419868618aeaa5fe8019c62421857d6",
- ) // v2.2.0
- .if_condition(gated())
- .add_with(("bun-version", "1.3.13"))
-}
-
-fn play_auth() -> Step<Use> {
- Step::new("Authenticate to Google Play")
- .uses(
- "google-github-actions",
- "auth",
- "7c6bc770dae815cd3e89ee6cdf493a5fab2cc093",
- ) // v3
- .id("auth")
- .if_condition(gated())
- .add_with((
- "workload_identity_provider",
- "${{ vars.GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER }}",
- ))
- .add_with(("service_account", "${{ vars.GOOGLE_PLAY_SERVICE_ACCOUNT }}"))
- .add_with(("token_format", "access_token"))
- .add_with((
- "access_token_scopes",
- "https://www.googleapis.com/auth/androidpublisher",
- ))
- .add_with(("create_credentials_file", false))
- .add_with(("export_environment_variables", false))
+ steps::setup_bun_pinned().if_condition(gated())
}
fn rerun_live_checks() -> Step<Run> {
Step::new("Re-run the check on PRs whose release is live")
.run(concat!(
include_str!("scripts/android_git_fetch.sh"),
+ include_str!("scripts/android_play_statuses.sh"),
include_str!("scripts/android_release_watch.sh")
))
.shell("bash")
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_native_check_live.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_native_check_live.sh
new file mode 100644
index 0000000000..6e78f1548d
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_native_check_live.sh
@@ -0,0 +1,41 @@
+set -euo pipefail
+# The Android merge gate proper: version code $VERSION_CODE must be live on
+# Google Play production, built from the Android native code of PR
+# #PR_NUMBER's *current* merge result (fetched through the API: a re-run
+# checks out the merge commit of the run's original event, which may predate
+# native code landing on main). This job cannot sign in to Play — only
+# workflows that run main's copy can — so it reads the `android-play/live`
+# status that Android Release Watch sets once the release is live. Any of the
+# PR's commits counts: web-only pushes after the release keep it valid, and
+# the native hash in the description pins it to this merge result.
+merge=$(pr_merge_commit)
+gh_fetch "$merge"
+native_hash=$(bun scripts/android-native.mjs hash "$merge")
+echo "Merge result ${merge:0:10}: Android native hash ${native_hash}"
+want=$(android_live_description "$VERSION_CODE" "$native_hash" "$PR_NUMBER")
+statuses=$(pr_commit_statuses android-play/live)
+while read -r sha state description; do
+ if [[ "$state" == success && "$description" == "$want" ]]; then
+ echo "${sha:0:10} is marked android-play/live: ${description}."
+ exit 0
+ fi
+done <<<"$statuses"
+echo "Android native changes require version code ${VERSION_CODE} to be live on Google Play before merging," \
+ "built from native tree ${native_hash}, but no commit of this PR is marked so (android-play/live)." >&2
+if [[ -n "$statuses" ]]; then
+ echo "android-play/live statuses on this PR's commits:" >&2
+ while read -r sha state description; do
+ echo " ${sha:0:10} ${state}: ${description}" >&2
+ done <<<"$statuses"
+fi
+cat >&2 <<'EOF'
+ - Not started yet? Add the `android-update` label to the PR to build, upload
+ and promote it.
+ - Promoted? Wait for Google review; the `Android Release Watch` workflow marks
+ the PR and re-runs this check within half an hour of the release.
+ - Native code changed since the release (pushed to the PR, or landed on main)?
+ Bump (`just android-bump`), commit, re-add `android-update`.
+ - If the native change doesn't break the native/web contract, add the
+ `skip-android-update` label instead.
+EOF
+exit 1
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_play_publish_comment.js b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_play_publish_comment.js
new file mode 100644
index 0000000000..da02c2b4a9
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_play_publish_comment.js
@@ -0,0 +1,71 @@
+// Android Play Publish's closing comment on the PR (actions/github-script).
+// A failure names the step that failed and, when it is one that logs its
+// output (steps::logged_run), quotes the end of that output.
+const fs = require('fs');
+const path = require('path');
+const env = process.env;
+const versionCode = env.VERSION_CODE || '?';
+const releaseName = env.RELEASE_NAME || `version code ${versionCode}`;
+const runUrl =
+ `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}` +
+ `/actions/runs/${context.runId}`;
+const runs = `[build](${env.BUILD_URL}), [publish](${runUrl})`;
+let body;
+if (env.JOB_STATUS === 'success') {
+ body = [
+ `🤖 Android ${releaseName} was uploaded to Google Play internal testing and submitted for a full production rollout (${runs}).`,
+ '',
+ 'When Google approves it, the version goes live, the **Android Release Watch** workflow',
+ 'marks this PR `android-play/live` and re-runs the **Android Native Check** within half an hour',
+ 'of that, and the PR becomes mergeable. To merge it the moment that happens, click',
+ '**Enable auto-merge** on this PR now (squash).',
+ 'After merge, the next prod deploy applies the Android native build floor committed in `min-native-build.json`.',
+ ].join('\n');
+} else {
+ let failedStep = null;
+ try {
+ const { data } = await github.rest.actions.listJobsForWorkflowRunAttempt({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ run_id: context.runId,
+ attempt_number: Number(env.GITHUB_RUN_ATTEMPT),
+ });
+ const job = data.jobs.find((j) => j.name === env.JOB_NAME);
+ failedStep = job?.steps.find((s) => s.conclusion === 'failure')?.name ?? null;
+ } catch (error) {
+ core.warning(`Could not list this job's steps: ${error.message}`);
+ }
+ const read = (file) => {
+ try {
+ return fs.readFileSync(path.join(env.RUNNER_TEMP, file), 'utf8');
+ } catch {
+ return '';
+ }
+ };
+ let tail = '';
+ if (failedStep && read('last-step.name').trim() === failedStep) {
+ const lines = read('last-step.log').replace(/\x1b\[[0-9;]*m/g, '').trimEnd().split('\n');
+ tail = lines.slice(-30).join('\n').slice(-3000);
+ }
+ const retry =
+ env.UPLOAD_OUTCOME === 'success'
+ ? [
+ `The bundle reached the internal track, so version code ${versionCode} is used up: bump`,
+ '(`cd apps/web && just android-bump`), commit, and re-add the `android-update` label.',
+ 'If only the promotion failed and the native code is unchanged, you can instead promote',
+ `version code ${versionCode} by hand with **Publish Android to Google Play** (\`operation=promote-production\`).`,
+ ].join('\n')
+ : 'Fix the problem, then remove and re-add the `android-update` label to retry.';
+ body = [
+ `🤖 Android Play release for ${releaseName} **failed**${failedStep ? ` at **${failedStep}**` : ''} (${runs}).`,
+ ...(tail ? ['', '```text', tail, '```'] : []),
+ '',
+ retry,
+ ].join('\n');
+}
+await github.rest.issues.createComment({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: Number(env.PR_NUMBER),
+ body,
+});
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_play_publish_verify.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_play_publish_verify.sh
new file mode 100644
index 0000000000..2354fe3ec6
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_play_publish_verify.sh
@@ -0,0 +1,100 @@
+set -euo pipefail
+# Android Play Publish runs main's copy for every completed Android Play
+# Release run. That run executed the PR's own copy of the workflow, so its
+# name, artifact and outcome prove nothing on their own: any PR can add a
+# workflow named "Android Play Release" that runs on any event. The
+# `android-update` label is the release decision, so publish only a build
+# tied to the person who added it, checking GitHub's records rather than
+# the run's:
+#
+# 1. it ran the release workflow file and its release job succeeded;
+# 2. its branch is the head of exactly one open same-repository PR into main;
+# 3. that PR still carries the label, and the label's latest event is an
+# add by a person (not a bot or token) with write access;
+# 4. that person started this run, within minutes of adding the label, so
+# a run from before a newer add, or from much later, does not qualify.
+#
+# This binds the build to that person, not to the label event itself: GitHub
+# doesn't record which activity created a run, and the branch's own copy of
+# the release workflow decides which activities build. A branch that edits
+# that workflow could also build on the person's other PR activity inside
+# the window, after a push they did not review. That gives nobody more than
+# adding the label already does: pushing to a same-repository branch needs
+# write access, which is all adding the label needs.
+#
+# The head guard (a later step) then checks the PR's native code is still the
+# built one. Needs GH_TOKEN, GH_REPO, RUN_ID, RUN_ATTEMPT, RUN_PATH,
+# RUN_ACTOR, RUN_CREATED_AT, HEAD_SHA, HEAD_BRANCH, and gh_fetch.
+skip() {
+ echo "$1"
+ echo "publish=false" >> "$GITHUB_OUTPUT"
+ exit 0
+}
+refuse() {
+ echo "Not publishing run ${RUN_ID}: $1" >&2
+ exit 1
+}
+
+if [[ "${RUN_PATH%%@*}" != .github/workflows/android-play-release.yml ]]; then
+ skip "Run ${RUN_ID} ran ${RUN_PATH}, not the Android Play Release workflow file; nothing to publish."
+fi
+build=$(gh api "repos/${GH_REPO}/actions/runs/${RUN_ID}/attempts/${RUN_ATTEMPT}/jobs" \
+ --jq '[.jobs[] | select(.name == "Android Play Release") | .conclusion] | first // ""')
+if [[ "$build" != success ]]; then
+ skip "Run ${RUN_ID}'s Android Play Release job did not succeed (${build:-absent}): another label, or a failed build. Nothing to publish."
+fi
+
+pr=$(gh pr list --repo "$GH_REPO" --head "$HEAD_BRANCH" --base main --state open \
+ --json number,isCrossRepository \
+ --jq '[.[] | select(.isCrossRepository == false)] | if length == 1 then .[0].number else "" end')
+if [[ -z "$pr" ]]; then
+ refuse "branch ${HEAD_BRANCH} is not the head of exactly one open same-repository PR into main."
+fi
+export PR_NUMBER=$pr
+echo "pr_number=${PR_NUMBER}" >> "$GITHUB_OUTPUT"
+echo "Run ${RUN_ID} built ${HEAD_SHA:0:10} for PR #${PR_NUMBER}."
+
+if [[ "$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json labels \
+ --jq 'any(.labels[]; .name == "android-update")')" != true ]]; then
+ refuse "PR #${PR_NUMBER} no longer carries the android-update label."
+fi
+event=$(gh api --paginate "repos/${GH_REPO}/issues/${PR_NUMBER}/events" \
+ --jq '.[] | select((.event == "labeled" or .event == "unlabeled") and .label.name == "android-update")
+ | {event, login: .actor.login, type: .actor.type, at: .created_at}' \
+ | jq -cs 'sort_by(.at) | last // empty')
+if [[ -z "$event" ]]; then
+ refuse "PR #${PR_NUMBER} has no android-update label event."
+fi
+kind=$(jq -r '.event' <<<"$event")
+login=$(jq -r '.login' <<<"$event")
+type=$(jq -r '.type' <<<"$event")
+at=$(jq -r '.at' <<<"$event")
+if [[ "$kind" != labeled ]]; then
+ refuse "the android-update label was last removed (${at}), not added."
+fi
+if [[ "$type" != User ]]; then
+ refuse "the android-update label was last added by ${login} (${type}); a person with write access must add it."
+fi
+if [[ "$login" != "$RUN_ACTOR" ]]; then
+ refuse "${login} added the android-update label last, but ${RUN_ACTOR} started this run, so this is not the run that label started."
+fi
+permission=$(gh api "repos/${GH_REPO}/collaborators/${login}/permission" --jq '.permission')
+if [[ "$permission" != admin && "$permission" != write ]]; then
+ refuse "${login}, who added the android-update label, has ${permission} access; releasing needs write access."
+fi
+label_epoch=$(jq -rn --arg t "$at" '$t | fromdateiso8601')
+run_epoch=$(jq -rn --arg t "$RUN_CREATED_AT" '$t | fromdateiso8601')
+if (( run_epoch < label_epoch - 60 || run_epoch > label_epoch + 600 )); then
+ refuse "this run was created at ${RUN_CREATED_AT}, but the android-update label was last added at ${at}, so the label did not start it. Re-add the label to release the PR's current head."
+fi
+echo "${login} (${permission} access) added android-update at ${at} and started this run at ${RUN_CREATED_AT}."
+
+gh_fetch "$HEAD_SHA"
+version_code=$(bun scripts/android-native.mjs version-code "$HEAD_SHA")
+version=$(git show "${HEAD_SHA}:apps/web/tauri/src-tauri/tauri.android.conf.json" | jq -r '.version')
+{
+ echo "version_code=${version_code}"
+ echo "release_name=${version} (${version_code})"
+ echo "publish=true"
+} >> "$GITHUB_OUTPUT"
+echo "Publishing Android ${version} (version code ${version_code})."
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_play_statuses.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_play_statuses.sh
new file mode 100644
index 0000000000..ace4111c2f
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_play_statuses.sh
@@ -0,0 +1,54 @@
+# --- Android Play commit statuses ---------------------------------------------
+# Only workflows that run main's copy may sign in to Google Play, so they
+# record what they learn as commit statuses on the PR's commits, where the
+# PR-side jobs (the merge gate, the drift check) read it:
+#
+# android-play/release set by Android Play Publish on the commit it built:
+# pending just before the production promotion, then
+# success or failure.
+# android-play/live set by Android Release Watch on the PR head once the
+# release is live on production.
+#
+# Readers match the descriptions exactly, so they are built only here.
+# Needs GH_TOKEN and GH_REPO; pr_commit_statuses also PR_NUMBER.
+
+# android_release_description <version code> <native hash>
+android_release_description() {
+ printf 'Version code %s (native tree %s)' "$1" "$2"
+}
+
+# android_live_description <version code> <native hash> <PR number>
+android_live_description() {
+ printf 'Version code %s is live on Google Play (native tree %s, PR #%s)' "$1" "$2" "$3"
+}
+
+# commit_status <sha> <context>: `<state> <description>` of the commit's latest
+# status with that context, or nothing.
+commit_status() {
+ gh api "repos/${GH_REPO}/commits/$1/status" \
+ --jq ".statuses[] | select(.context == \"$2\") | \"\(.state) \(.description)\""
+}
+
+# pr_commit_statuses <context>: `<sha> <state> <description>` for each of PR
+# #PR_NUMBER's last 100 commits that has a status with that context (its
+# latest one), states in lower case like the REST API's.
+pr_commit_statuses() {
+ gh api graphql -F owner="${GH_REPO%%/*}" -F name="${GH_REPO#*/}" -F pr="$PR_NUMBER" -F context="$1" \
+ -f query='query($owner: String!, $name: String!, $pr: Int!, $context: String!) {
+ repository(owner: $owner, name: $name) {
+ pullRequest(number: $pr) {
+ commits(last: 100) { nodes { commit { oid status { context(name: $context) { state description } } } } }
+ }
+ }
+ }' \
+ --jq '.data.repository.pullRequest.commits.nodes[].commit
+ | select(.status.context != null)
+ | "\(.oid) \(.status.context.state | ascii_downcase) \(.status.context.description)"'
+}
+
+# set_commit_status <sha> <context> <state> <description>, linking this run.
+set_commit_status() {
+ gh api "repos/${GH_REPO}/statuses/$1" -f context="$2" -f state="$3" -f description="$4" \
+ -f target_url="${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" >/dev/null
+}
+# ------------------------------------------------------------------------------
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_drift_promoted.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_drift_promoted.sh
new file mode 100644
index 0000000000..f9da15fb50
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_drift_promoted.sh
@@ -0,0 +1,46 @@
+set -euo pipefail
+# Was the stale bundle — version code $VERSION_CODE, released from
+# $BEFORE_SHA or an earlier commit of PR #PR_NUMBER — submitted to Google
+# Play production? This job runs the PR's code and cannot sign in to Play, so
+# it reads the android-play/release status Android Play Publish sets on the
+# commit it built: success means submitted, pending or failure that it may
+# have been. A publish run still in progress may be promoting right now, so
+# wait for it first. Outputs promoted=true|false, or nothing when unknown.
+# BEFORE_SHA is checked directly because a force-push drops it from the PR.
+deadline=$(( $(date +%s) + 10 * 60 ))
+while true; do
+ if ! running=$(gh run list --repo "$GH_REPO" --workflow android-play-publish.yml --json status \
+ --jq '[.[] | select(.status != "completed")] | length'); then
+ echo "Could not list Android Play Publish runs; production status unknown."
+ exit 0
+ fi
+ if [[ "$running" == 0 ]]; then
+ break
+ fi
+ if (( $(date +%s) > deadline )); then
+ echo "An Android Play Publish run is still in progress; production status unknown."
+ exit 0
+ fi
+ echo "Waiting for ${running} Android Play Publish run(s) to finish."
+ sleep 15
+done
+if ! before=$(commit_status "$BEFORE_SHA" android-play/release) || ! others=$(pr_commit_statuses android-play/release); then
+ echo "Could not read android-play/release statuses; production status unknown."
+ exit 0
+fi
+promoted=false
+while read -r sha state description; do
+ [[ "$description" == "Version code ${VERSION_CODE} ("* ]] || continue
+ echo "${sha:0:10}: android-play/release ${state}: ${description}"
+ if [[ "$state" == success ]]; then
+ promoted=true
+ break
+ fi
+ promoted=unknown
+done < <({ [[ -z "$before" ]] || printf '%s %s\n' "$BEFORE_SHA" "$before"; } && printf '%s\n' "$others")
+if [[ "$promoted" == unknown ]]; then
+ echo "Android Play Publish may have promoted version code ${VERSION_CODE}: production status unknown."
+else
+ echo "promoted=${promoted}" >> "$GITHUB_OUTPUT"
+ echo "Version code ${VERSION_CODE} submitted to production: ${promoted}."
+fi
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_head_guard.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_head_guard.sh
index 0ea239cae6..84453b784d 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_head_guard.sh
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_head_guard.sh
@@ -1,29 +1,45 @@
set -euo pipefail
-# Last check before uploading: the bundle must still describe the native code
+# Last check before uploading (and before promoting): the bundle must still describe the native code
# the merge gate will hash — that of the PR's merge result — or it could never
# pass the gate, and a promoted Play release cannot be withdrawn. Two things
# can move while a build runs: the PR head (a native push; the drift workflow
# cancels runs after the fact, but better not to upload at all) and main
-# (another Android PR merged).
-built=$(bun scripts/android-native.mjs hash HEAD)
+# (another Android PR merged). The build is HEAD, or BUILT_SHA when set (the
+# publisher judges a PR build from main's checkout). GUARD_STAGE=promote words
+# it for the check before the production promotion, after the upload to the
+# internal track has used the version code up.
+if [[ "${GUARD_STAGE:-upload}" == promote ]]; then
+ verb=promoting
+ done_msg="Promoting"
+ retry="Version code is used up on the internal track: bump (cd apps/web && just android-bump), commit, and re-add the android-update label."
+else
+ verb=uploading
+ done_msg="Uploading"
+ retry="Re-add the android-update label to release the current head."
+fi
+built_sha=${BUILT_SHA:-$(git rev-parse HEAD)}
+if [[ -n "${BUILT_SHA:-}" ]]; then
+ gh_fetch "$BUILT_SHA"
+fi
+built=$(bun scripts/android-native.mjs hash "$built_sha")
head_sha=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json headRefOid --jq '.headRefOid')
-if [[ "$head_sha" == "$(git rev-parse HEAD)" ]]; then
+if [[ "$head_sha" == "$built_sha" ]]; then
echo "PR head unchanged (${head_sha:0:10}); native hash ${built:0:10} is current."
else
gh_fetch "$head_sha"
current=$(bun scripts/android-native.mjs hash "$head_sha")
if [[ "$current" != "$built" ]]; then
echo "Android native code changed on PR #${PR_NUMBER} while this release was building" \
- "(${built:0:10} → ${current:0:10}). Not uploading the stale bundle." >&2
- echo "Re-add the android-update label to release the current head." >&2
+ "(${built:0:10} → ${current:0:10}). Not ${verb} the stale bundle." >&2
+ echo "$retry" >&2
exit 1
fi
echo "PR head moved to ${head_sha:0:10} but its Android native code is unchanged (${built:0:10})."
fi
if ! merge_result_native_check "bun scripts/android-native.mjs hash" "bun scripts/android-native.mjs listing" gh_fetch; then
- echo "Android native code landed on ${BASE_BRANCH} while this release was building. Not uploading the bundle" \
+ echo "Android native code landed on ${BASE_BRANCH} while this release was building. Not ${verb} the bundle" \
"(native hash ${built:0:10}): the merge gate could never accept it." >&2
echo "Merge ${BASE_BRANCH} into the PR, bump (cd apps/web && just android-bump), commit, and re-add the android-update label." >&2
exit 1
fi
-echo "Uploading the bundle (native hash ${built:0:10})."
+echo "${done_msg} the bundle (native hash ${built:0:10})."
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_preconditions.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_preconditions.sh
index f1ba130e3a..43ef184c24 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_preconditions.sh
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_preconditions.sh
@@ -47,8 +47,10 @@ fi
echo "version_code=${version_code}" >> "$GITHUB_OUTPUT"
echo "Releasing Android version code ${version_code}."
-# (`gh pr checks` names are job names, not workflow names.)
-ours='^(Android Native Check|Android Play Release|Re-run the native check|Web App Status Check|Android Release Drift|iOS Native Check)'
+# (`gh pr checks` names are job names, not workflow names, plus the contexts
+# of commit statuses, such as the android-play/* ones Android Play Publish
+# and Android Release Watch set.)
+ours='^(Android Native Check|Android Play Release|Re-run the native check|Web App Status Check|Android Release Drift|iOS Native Check|android-play/)'
deadline=$(( $(date +%s) + WAIT_MINUTES * 60 ))
while true; do
checks=$(gh pr checks "$PR_NUMBER" --repo "$GH_REPO" --json name,bucket \
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_watch.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_watch.sh
index 55faa6c4ac..174c00a0d2 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_watch.sh
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_watch.sh
@@ -3,16 +3,18 @@ set -euo pipefail
# Google Play whether the version code committed at the PR head is live on
# production, built from the Android native code of the PR's merge result
# (`merge` is GitHub's test merge commit; the gate hashes the same). When it
-# is, and the PR's latest `Android Native Check` job (of the web app PR checks
-# run) failed — it fails until the release is live — re-run that job so the
-# gate, and the `Web App Status Check` that depends on it, go green without
-# anyone clicking "Re-run". GH_TOKEN needs actions:write + pull-requests:write;
-# GOOGLE_PLAY_ACCESS_TOKEN the androidpublisher scope.
+# is, mark the PR head `android-play/live` (the gate cannot ask Play, so it
+# reads that status), and if the PR's latest `Android Native Check` job (of
+# the web app PR checks run) failed — it fails until the release is live —
+# re-run that job so the gate, and the `Web App Status Check` that depends on
+# it, go green without anyone clicking "Re-run". GH_TOKEN needs actions:write,
+# pull-requests:write and statuses:write; GOOGLE_PLAY_ACCESS_TOKEN the
+# androidpublisher scope.
cd apps/web
conf_path="apps/web/tauri/src-tauri/tauri.android.conf.json"
check_pr() {
- local pr=$1 number sha merge native_hash version_code run run_id status run_url job conclusion job_id reruns
+ local pr=$1 number sha merge native_hash version_code live run run_id status run_url job conclusion job_id reruns
number=$(jq -r '.number' <<<"$pr")
sha=$(jq -r '.sha' <<<"$pr")
merge=$(jq -r '.merge // empty' <<<"$pr")
@@ -32,6 +34,13 @@ check_pr() {
return 0
fi
echo " live on Google Play production"
+ live=$(android_live_description "$version_code" "$native_hash" "$number")
+ if [[ "$(commit_status "$sha" android-play/live)" == "success ${live}" ]]; then
+ echo " ${sha:0:10} already marked android-play/live"
+ else
+ set_commit_status "$sha" android-play/live success "$live"
+ echo " marked ${sha:0:10} android-play/live"
+ fi
run=$(gh run list --workflow web-app-check-main.yml --commit "$sha" \
--json databaseId,status,url --limit 1 --jq '.[0] // empty')
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/merge_result_native_check.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/merge_result_native_check.sh
index 6eeb069302..09f7a2e4c2 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/merge_result_native_check.sh
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/merge_result_native_check.sh
@@ -1,7 +1,8 @@
# --- merge result native check ------------------------------------------------
# merge_result_native_check <hash> <listing> <fetch>: is the native code of
-# PR #PR_NUMBER's merge result the native code of HEAD, the code this run
-# built or is about to build? The merge gate hashes the merge result, so a
+# PR #PR_NUMBER's merge result the native code of the commit this run built
+# or is about to build — BUILT_SHA when set (a job that checked out other
+# code, such as main's, to judge it), else HEAD? The merge gate hashes the merge result, so a
# build that differs from it could never pass the gate. <hash> / <listing>
# print a commit's native hash / the listing behind it; <fetch> makes a
# commit available (the iOS and Android helpers differ). Needs GH_TOKEN,
@@ -18,7 +19,7 @@ merge_result_native_check() {
# Callers run this under `if !`, which turns off `set -e` here, so every
# lookup is checked: an empty commit hashes the same on both sides and would
# pass an unchecked comparison.
- built=$(git rev-parse HEAD)
+ built=${BUILT_SHA:-$(git rev-parse HEAD)}
if ! built_hash=$($hash "$built"); then
echo "Could not hash this build's native code (${built:0:10})." >&2
return 1
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/release_label_check.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/release_label_check.sh
index db1f123b66..a02b111667 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/release_label_check.sh
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/release_label_check.sh
@@ -33,7 +33,7 @@ announce_release() {
steps="builds the app, uploads it to TestFlight and submits it for App Review"
else
what="Android version code $(jq -r '.bundle.android.versionCode' <<<"$conf")"
- steps="builds the App Bundle, uploads it to the internal track and promotes it to production"
+ steps="builds the App Bundle, and **Android Play Publish** uploads it to the internal track and promotes it to production"
fi
gh pr comment "$PR_NUMBER" --repo "$GH_REPO" --body "🚀 **${WORKFLOW}** started for ${what} at ${HEAD_SHA:0:10} ([workflow run](${url})). It ${steps}, then comments here with the result."
echo "PR #${PR_NUMBER}: ${WORKFLOW} started for ${what}: ${url}"
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/steps.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/steps.rs
index f34da7328f..419cc064ea 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/steps.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/steps.rs
@@ -82,6 +82,51 @@ pub fn setup_bun() -> Step<Use> {
Step::new("Setup Bun").uses("oven-sh", "setup-bun", "v2")
}
+/// `oven-sh/setup-bun`, SHA-pinned with an exact Bun version, for the native
+/// release workflows that run the `apps/web/scripts` release helpers.
+pub fn setup_bun_pinned() -> Step<Use> {
+ Step::new("Setup Bun")
+ .uses(
+ "oven-sh",
+ "setup-bun",
+ "0c5077e51419868618aeaa5fe8019c62421857d6",
+ ) // v2.2.0
+ .add_with(("bun-version", "1.3.13"))
+}
+
+/// Keyless Google Play access (Workload Identity Federation through the
+/// repository variables `GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER` /
+/// `GOOGLE_PLAY_SERVICE_ACCOUNT`), as step `auth`: an `androidpublisher`
+/// access token, plus a credentials file for actions that want one. The job
+/// needs `id-token: write`. Google's provider admits only workflows that run
+/// `main`'s copy (see "Keyless publishing credentials" in
+/// docs/development/android.md), so never use this in a `pull_request` job:
+/// it would run the PR's code with the publishing identity, and the provider
+/// rejects it anyway.
+pub fn google_play_auth(credentials_file: bool) -> Step<Use> {
+ Step::new("Authenticate to Google Play")
+ .uses(
+ "google-github-actions",
+ "auth",
+ "7c6bc770dae815cd3e89ee6cdf493a5fab2cc093",
+ ) // v3
+ .id("auth")
+ .add_with((
+ "workload_identity_provider",
+ "${{ vars.GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER }}",
+ ))
+ .add_with(("service_account", "${{ vars.GOOGLE_PLAY_SERVICE_ACCOUNT }}"))
+ .add_with(("token_format", "access_token"))
+ .add_with((
+ "access_token_scopes",
+ "https://www.googleapis.com/auth/androidpublisher",
+ ))
+ .when(!credentials_file, |step| {
+ step.add_with(("create_credentials_file", false))
+ })
+ .add_with(("export_environment_variables", false))
+}
+
/// Install the Rust toolchain only (no sccache, no cache) — for the lightweight
/// `path-check` and workflow-drift jobs.
pub fn setup_rust_light() -> Step<Use> {
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/android_native_check.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/android_native_check.rs
index 5aef45975d..a2b5a20eaf 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/android_native_check.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/android_native_check.rs
@@ -9,18 +9,18 @@
//! workflow through `android-native.mjs`: every tracked file under
//! `apps/web/tauri` minus iOS/desktop-only paths, plus the client cache
//! wasm version).
-//! 2. When it changed, asks Google Play whether that version code is a
-//! published production release (through review and rolled out) built
-//! from the native code of the PR's current merge result (the provenance
-//! stamp in the release notes),
-//! and fails with instructions otherwise — add the `android-update` label
-//! to run [`super::super::android_play_release`];
-//! [`super::super::android_release_watch`] re-runs this job once the
-//! release is live.
+//! 2. When it changed, requires that version code to be a published
+//! production release (through review and rolled out) built from the
+//! native code of the PR's current merge result, and fails with
+//! instructions otherwise — add the `android-update` label to run
+//! [`super::super::android_play_release`].
//!
-//! Play access is keyless (Workload Identity Federation), so the job needs
-//! `id-token: write`; fork PRs don't get that and fail closed at the auth
-//! step. The `skip-android-update` label bypasses the whole gate, bump
+//! This job runs the PR's code, so it cannot sign in to Google Play: only
+//! workflows that run `main`'s copy can. [`super::super::android_release_watch`]
+//! asks Play instead, marks a PR whose release is live with the
+//! `android-play/live` commit status (version code, native hash and PR
+//! number in its description), and re-runs this job, which then finds the
+//! status. The `skip-android-update` label bypasses the whole gate, bump
//! included, for native changes that don't break the native/web contract,
//! like `skip-ios-update`: the bump only feeds the Play release, which
//! re-checks it before building, and a PR that skips the gate never
@@ -34,7 +34,7 @@
use gh_workflow::{Expression, Job, Level, Permissions, Run, Step, Use};
-use crate::workflows::runners;
+use crate::workflows::{runners, steps};
/// The job's id in the web app check workflow.
pub(super) const JOB_ID: &str = "android-native-check";
@@ -50,15 +50,14 @@ pub(super) fn job() -> Job {
.permissions(
Permissions::default()
.contents(Level::Read)
- .id_token(Level::Write)
- .pull_requests(Level::Read),
+ .pull_requests(Level::Read)
+ .statuses(Level::Read),
)
.add_step(super::checkout("Checkout PR merge commit", false))
.add_step(setup_bun())
.add_step(read_labels())
.add_step(version_check())
.add_step(floor_check())
- .add_step(play_auth())
.add_step(require_live())
.add_step(skip_notice())
}
@@ -68,13 +67,7 @@ fn gated() -> Expression {
}
fn setup_bun() -> Step<Use> {
- Step::new("Setup Bun")
- .uses(
- "oven-sh",
- "setup-bun",
- "0c5077e51419868618aeaa5fe8019c62421857d6",
- ) // v2.2.0
- .add_with(("bun-version", "1.3.13"))
+ steps::setup_bun_pinned()
}
/// Unless the label skips the gate, the version code must exceed the base
@@ -135,46 +128,16 @@ fn read_labels() -> Step<Run> {
.add_env(("PR_NUMBER", "${{ github.event.pull_request.number }}"))
}
-fn play_auth() -> Step<Use> {
- Step::new("Authenticate to Google Play")
- .uses(
- "google-github-actions",
- "auth",
- "7c6bc770dae815cd3e89ee6cdf493a5fab2cc093",
- ) // v3
- .id("auth")
- .if_condition(gated())
- .add_with((
- "workload_identity_provider",
- "${{ vars.GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER }}",
- ))
- .add_with(("service_account", "${{ vars.GOOGLE_PLAY_SERVICE_ACCOUNT }}"))
- .add_with(("token_format", "access_token"))
- .add_with((
- "access_token_scopes",
- "https://www.googleapis.com/auth/androidpublisher",
- ))
- .add_with(("create_credentials_file", false))
- .add_with(("export_environment_variables", false))
-}
-
/// The gate proper: the committed version code must be live on production,
/// built from the Android native code of the PR's *current* merge result
-/// (fetched through the API: a re-run checks out the merge commit of the
-/// run's original event, which may predate native code landing on main).
+/// (see the script).
fn require_live() -> Step<Run> {
Step::new("Require the Play release to be live")
.run(concat!(
include_str!("../scripts/android_git_fetch.sh"),
include_str!("../scripts/pr_merge_commit.sh"),
- r#"set -euo pipefail
-merge=$(pr_merge_commit)
-gh_fetch "$merge"
-native_hash=$(bun scripts/android-native.mjs hash "$merge")
-echo "Merge result ${merge:0:10}: Android native hash ${native_hash}"
-bun scripts/android-play-status.mjs --version-code "$VERSION_CODE" --require-live \
- --native-hash "$native_hash" --pr "$PR_NUMBER"
-"#
+ include_str!("../scripts/android_play_statuses.sh"),
+ include_str!("../scripts/android_native_check_live.sh")
))
.if_condition(gated())
.shell("bash")
@@ -186,10 +149,6 @@ bun scripts/android-play-status.mjs --version-code "$VERSION_CODE" --require-liv
"VERSION_CODE",
"${{ steps.android-version.outputs.version_code }}",
))
- .add_env((
- "GOOGLE_PLAY_ACCESS_TOKEN",
- "${{ steps.auth.outputs.access_token }}",
- ))
}
fn skip_notice() -> Step<Run> {
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/test.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/test.rs
index 5f49befa89..35bb984a99 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/test.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/test.rs
@@ -18,8 +18,11 @@ fn android_native_check_is_an_unconditional_required_merge_check() {
"the base is the merge commit's first parent, not the event payload: {android}"
);
assert!(android.contains("bun scripts/android-version-check.mjs"));
- assert!(android.contains("bun scripts/android-play-status.mjs --version-code"));
- assert!(android.contains("id-token: write"));
+ // The gate runs the PR's code, so it reads the watcher's commit status
+ // instead of signing in to Google Play.
+ assert!(android.contains("pr_commit_statuses android-play/live"));
+ assert!(android.contains("statuses: read"));
+ assert!(!android.contains("id-token"));
// skip-android-update bypasses the bump too, like skip-ios-update: the
// labels are read first, and the version check only runs without it.
let labels = android.find("id: labels").expect("labels step");