优化 Gitea 并行构建、重试与 Windows 更新发布 #5

Merged
lingjhf merged 11 commits from ci/gitea-parallel-build-retries into main 2026-10-06 08:21:10 +00:00
34 changed files with 2442 additions and 254 deletions

No files matched your search

+69
View File
@@ -0,0 +1,69 @@
# Gitea Windows and Android builds
The Windows x64 host runner needs Flutter 3.47.5, Python, Node, Visual Studio C++,
JDK 21 and Android SDK 36. The native cutdex_windows Release and cutdex_android
Maven packages must be published before building this app. The SDK Git dependency
is pinned to Gitea; the runner account needs SSH access to that private repository.
Set CUTDEX_GITEA_TOKEN in repository Actions Secrets with repository read and
package read access. It authenticates private Gitea native package downloads.
The Android APK includes ARM64 and x86_64, uses the production flavor and currently
uses the project's debug signing configuration. Configure formal signing before
shipping a production signed Android release. The Windows ZIP includes the whole
Flutter Release directory and passes the PE dependency audit. Processing workers
and optional models are separate; these four repositories contain no worker bundle.
PR/main CI analyzes and tests the app, builds both platforms, and uploads
cutdex-release-packages including SHA256SUMS and a release manifest. It also saves
cutdex-release-metadata containing only the manifest, checksums, Windows update
index and audit report. Platform, complete and metadata artifacts retain 30 days. Protect main
with `Gitea CI / Gitea CI passed (pull_request)`.
Windows compilation and packaging are separate jobs. Compilation saves the
unpackaged Release directory as `cutdex-windows-app` for 30 days; packaging
downloads it and runs the existing PE audit and Velopack tools. Rerunning a failed
packaging job reuses this app without recompiling. Assembly and Release jobs
similarly reuse their upstream artifacts. Use the failed-job rerun option: a
whole-workflow rerun executes compilation again. A job always restarts from its
first step. Saving the Windows app adds one artifact transfer between the jobs.
CI artifact uploads attempt at most three times, waiting 5 and 15 seconds between
attempts and replacing incomplete artifacts of the same job-owned name. Release
attachment uploads use the same bounded delays for temporary HTTP/network errors,
and check for already saved filenames before repeating a POST. Permanent errors
fail immediately and final attachment byte verification remains required. If the
Windows app cannot be saved after all attempts, its build job still needs to be
rerun. Draft creation and final publication are not automatically retried.
After main CI succeeds, create v<pubspec version> at that exact commit, or manually
dispatch the Release workflow with the existing tag. Release preparation selects
a successful main ci.yml run for the exact tagged commit and requires unexpired
cutdex-android-build, cutdex-windows-build and cutdex-release-metadata artifacts. It creates a draft bound to both that commit and
that CI run. Release jobs never rebuild the app or reinstall Flutter dependencies.
Android and Windows independently download their platform artifacts from the
selected CI run and immediately upload them to the draft. These jobs run in
parallel. The final job accepts only the compact metadata artifact from that same
CI run. Complete binary archives cannot substitute for platform packages or
metadata. Missing, expired or duplicate required artifacts block preparation
before any draft is created. Platform uploads check attachment presence without
reading back their bytes. Before publication, every attachment is read back once
and verified against trusted SHA256 checksums; the full update package also
matches its index SHA1 and size. Upload and verification batches use at most two
requests per job. Verification reads in 1 MiB chunks. Tag, CI, draft and attachment
ID/name bindings are rechecked before the Release is made public.
A failed upload leaves the draft unpublished with successful uploads retained.
Manual dispatch with the same tag resumes the original CI run, even if another CI
for that commit has since succeeded. Matching attachments are reused; changed or
unrelated attachments block publication rather than being replaced. If the
original platform or metadata artifacts have expired, release preparation fails and requires
operator attention. Published Releases are never overwritten. The built-in
GITEA_TOKEN handles release writes and Actions artifact reads; no separate
release-write PAT is required. Do not commit credentials or keystores.
PR/main CI produces Actions artifacts without creating Releases. If a tag is pushed
before main CI succeeds, release preparation fails without creating a draft; retry
the Release workflow once CI has finished. This design overlaps platform uploads,
not main CI builds with Release uploads. There is no legacy whole-archive
promotion entry point or format fallback.
+100
View File
@@ -0,0 +1,100 @@
# CI build performance
The workflow runs checks first, then Android and Windows compilation concurrently.
Windows compilation saves `cutdex-windows-app`; an independent Windows job
downloads that app, audits it and creates Velopack packages. Packaging needs
neither Flutter dependencies nor another Windows compilation. The Android job
builds the APK. The final job downloads only platform packages and
validates the complete release manifest, update feed and checksums. The public
artifact remains `cutdex-release-packages`.
Build jobs explicitly use persistent runner-user Pub and Gradle caches, respecting
existing `PUB_CACHE` and `GRADLE_USER_HOME` overrides. Gradle task output caching is
enabled for CI. Do not clear these caches between runs. Each job must have its own
checkout; do not share a Flutter `build/` or `.dart_tool/` directory between jobs.
With an ephemeral runner, these user directories must be persisted separately.
Build commands keep Flutter's default Pub preparation after the explicit locked
resolution. Do not use `--no-pub`: Flutter also regenerates release plugin
registrants in that preparation, removing dev-only plugins such as integration_test.
The runner needs at least two execution slots. The local runner configuration at
`D:/workspace/gitea-stack/runner/config.yaml` currently has `capacity: 2`. The host
has 12 logical processors and approximately 16 GB RAM; the Android job retains its
3 GB heap and four-worker limit to leave room for concurrent Windows compilation.
`prepare-package-tools.ps1` installs pinned `pefile` and `vpk` on first use under
the runner user's `%LOCALAPPDATA%/Cutdex/ci-tools/`. Later builds reuse them after
version checks. Python interpreter identity and tool versions isolate the cache,
and a mutex protects installation across concurrent workflows. .NET setup remains
in the Windows packaging job to provide SDK 10 and the runtime required by `vpk`.
The .NET installation uses the runner user's `Cutdex/ci-tools/dotnet` directory
through `DOTNET_INSTALL_DIR` and `DOTNET_ROOT`, so setup needs no administrator
access and later jobs reuse the installed SDK and runtime.
The Windows build verifies that the resolved deskup native SDK matches the pinned
Velopack version before saving the app. Packaging imports no Flutter package
configuration and independently verifies the installed vpk version.
APK and Windows package uploads use `compression-level: 0` to avoid recompressing
already compressed artifacts. The saved Windows app uses compression level 1,
preserves nested and hidden runtime assets, and excludes the same debug files and
optional workers omitted by packaging. The saved app, platform packages, compact
metadata and validated release artifact all retain 30 days.
This host runs both Gitea and the runner. The workflows set
`CUTDEX_GITEA_INTERNAL_URL=http://127.0.0.1:3000` and override `ACTIONS_RESULTS_URL`
on artifact upload/download steps, so those transfers stay on the host instead of
looping through the public FRP tunnel. Release API uploads and byte verification
also use this loopback endpoint; tooling rewrites only the validated public Gitea
origin. The server's public URL remains `https://git.orangraph.com`, and the runner
registration is unchanged. These workflow labels require this shared-host layout;
configure a reachable private endpoint before using runners on other hosts.
Checkout uses the same endpoint through its `github-server-url` input, retaining
the requested commit/tag and disabling persisted credentials. Release requests
retain the public Host header so Gitea response links pass the public-origin checks.
Compare warm CI runs after the first cache fill. Measure checks, Android compile,
Windows compile, packaging and artifact transfer separately. Total duration follows
the slower platform branch, plus checks and final assembly; no fixed speedup is
assumed. Release audits and artifact validation remain mandatory.
## Failure recovery
Use Gitea's failed-job rerun rather than rerunning the entire workflow. A job
reruns from its first step, including downstream dependent jobs. Once the Windows
app artifact has been saved, a Windows packaging failure can be retried without
recompilation. Assembly failures reuse the saved Android and Windows packages;
Release failures reuse the successful main CI. Splitting Windows adds one app
upload/download on successful runs in exchange for this recovery point.
Every CI artifact upload uses the local `upload-artifact` composite, with at most
three action attempts and 5/15-second delays. Attempts replace incomplete
artifacts with the same name; each name belongs to one producing job. Exhausted
retries fail the job. If the first Windows app checkpoint cannot be uploaded,
the build job must still be rerun; it has no saved app to restore.
Release attachment uploads retry temporary network errors, HTTP 408/429 and
500/502/503/504 up to three POST attempts per file, also with 5/15-second delays.
The specific FRP HTML "Not Found" page observed during tunnel reconnection is
also treated as temporary; ordinary Gitea API or HTML 404 responses still fail.
Before retrying a POST, the uploader checks whether Gitea already saved the named
attachment, including after the final response is lost. This avoids duplicate
uploads after a timeout. Authorization, invalid-input and other permanent errors
fail immediately. No draft creation or publication PATCH is automatically retried.
Attachment-list reads have their own bounded retries. Final byte verification
remains mandatory even when an existing filename is reused.
The tag/manual Release workflow reuses a successful main CI for the exact tagged
commit; it performs no Flutter builds, dependency resolution or Windows packaging.
A prepare job binds the draft and both platform upload jobs to one CI run. Android
and Windows independently fetch and upload their existing packages in parallel.
Publication requires the small cutdex-release-metadata artifact; it never
downloads the combined binary artifact. Missing or expired metadata/platform
artifacts fail preparation, with no old-format fallback. Every remote file is read and verified once, immediately
before publication, with two verification workers and 1 MiB chunks. Platform
upload steps check presence without repeating binary readbacks. Each upload
batch also uses at most two workers; while both platform jobs run, Android can
have one upload in flight alongside two Windows uploads.
Retries retain the original CI-run binding. Ordinary CI never creates
drafts. Wait for main CI success before tagging or retry Release after it finishes;
platform Release uploads overlap each other, not the original main builds.
-26
View File
@@ -1,26 +0,0 @@
# Gitea Windows and Android builds
The Windows x64 host runner needs Flutter 3.47.5, Python, Node, Visual Studio C++,
JDK 21 and Android SDK 36. The native cutdex_windows Release and cutdex_android
Maven packages must be published before building this app. The SDK Git dependency
is pinned to Gitea; the runner account needs SSH access to that private repository.
Set CUTDEX_GITEA_TOKEN in repository Actions Secrets with repository read and
package read access. It authenticates private Gitea native package downloads.
The Android APK includes ARM64 and x86_64, uses the production flavor and currently
uses the project's debug signing configuration. Configure formal signing before
shipping a production signed Android release. The Windows ZIP includes the whole
Flutter Release directory and passes the PE dependency audit. Processing workers
and optional models are separate; these four repositories contain no worker bundle.
PR/main CI analyzes and tests the app, builds both platforms, and uploads
cutdex-release-packages including SHA256SUMS and a release manifest. Protect main
with `Gitea CI / Gitea CI passed (pull_request)`.
After main CI succeeds, create v<pubspec version> at that exact commit. The Release
workflow downloads the existing CI artifact, requires both APK and Windows ZIP,
checks their digests, uploads to a draft Release, verifies remote bytes, then
publishes it. It refuses to overwrite a published Release. A manual dispatch with
the existing tag can retry an interrupted draft publication. The built-in GITEA_TOKEN
handles release writes and Actions artifact reads; no separate release-write PAT
is required. Do not commit credentials or keystores.
+69
View File
@@ -0,0 +1,69 @@
name: Upload CI artifact with bounded retries
description: Save an artifact with at most three attempts, replacing incomplete uploads of the same name.
inputs:
name:
description: Artifact name, unique to this job in the workflow run
required: true
path:
description: Files and directories to upload
required: true
compression-level:
description: ZIP compression level
default: '0'
retention-days:
description: Artifact retention in days
default: '30'
runs:
using: composite
steps:
- name: Upload artifact (attempt 1 of 3)
id: first
continue-on-error: true
uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: ${{ inputs.name }}
path: ${{ inputs.path }}
compression-level: ${{ inputs.compression-level }}
retention-days: ${{ inputs.retention-days }}
if-no-files-found: error
include-hidden-files: true
overwrite: true
- name: Wait before second upload attempt
if: ${{ !cancelled() && steps.first.outcome == 'failure' }}
shell: pwsh
run: Start-Sleep -Seconds 5
- name: Upload artifact (attempt 2 of 3)
id: second
if: ${{ !cancelled() && steps.first.outcome == 'failure' }}
continue-on-error: true
uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: ${{ inputs.name }}
path: ${{ inputs.path }}
compression-level: ${{ inputs.compression-level }}
retention-days: ${{ inputs.retention-days }}
if-no-files-found: error
include-hidden-files: true
overwrite: true
- name: Wait before final upload attempt
if: ${{ !cancelled() && steps.first.outcome == 'failure' && steps.second.outcome == 'failure' }}
shell: pwsh
run: Start-Sleep -Seconds 15
- name: Upload artifact (attempt 3 of 3)
id: third
if: ${{ !cancelled() && steps.first.outcome == 'failure' && steps.second.outcome == 'failure' }}
uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: ${{ inputs.name }}
path: ${{ inputs.path }}
compression-level: ${{ inputs.compression-level }}
retention-days: ${{ inputs.retention-days }}
if-no-files-found: error
include-hidden-files: true
overwrite: true
+179 -22
View File
@@ -13,57 +13,213 @@ concurrency:
cancel-in-progress: true cancel-in-progress: true
env: env:
PYTHONUTF8: '1' PYTHONUTF8: '1'
CUTDEX_GITEA_INTERNAL_URL: http://127.0.0.1:3000
GIT_CONFIG_COUNT: '2' GIT_CONFIG_COUNT: '2'
GIT_CONFIG_KEY_0: core.autocrlf GIT_CONFIG_KEY_0: core.autocrlf
GIT_CONFIG_VALUE_0: 'false' GIT_CONFIG_VALUE_0: 'false'
GIT_CONFIG_KEY_1: core.eol GIT_CONFIG_KEY_1: core.eol
GIT_CONFIG_VALUE_1: lf GIT_CONFIG_VALUE_1: lf
jobs: jobs:
build: quality:
name: Windows x64 and Android name: Check code and tests
runs-on: cutdex-windows-x64 runs-on: cutdex-windows-x64
env: env:
GITEA_ACTOR: lingjhf GITEA_ACTOR: lingjhf
CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }} CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }}
steps: steps:
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - name: Check out source
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with: with:
persist-credentials: false persist-credentials: false
- name: Verify toolchains github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Configure persistent build caches
run: ./tool/gitea/prepare-build-cache.ps1
- name: Verify Flutter version and configure Java
run: | run: |
$version = flutter --version --machine | ConvertFrom-Json $version = flutter --version --machine | ConvertFrom-Json
if ($version.frameworkVersion -ne '3.47.5') { throw 'Flutter 3.47.5 required.' } if ($version.frameworkVersion -ne '3.47.5') { throw 'Flutter 3.47.5 required.' }
flutter config --jdk-dir=$env:JAVA_HOME flutter config --jdk-dir=$env:JAVA_HOME
if ($LASTEXITCODE -ne 0) { throw 'Flutter JDK setup failed.' } if ($LASTEXITCODE -ne 0) { throw 'Flutter JDK setup failed.' }
- run: flutter pub get --enforce-lockfile - name: Resolve locked Flutter dependencies
- run: dart analyze --fatal-infos run: flutter pub get --enforce-lockfile
- run: flutter test --reporter expanded test packages/cutdex_ui/test packages/cutdex_native/test - name: Analyze Dart code
- name: Bound Android build memory on the shared runner run: dart analyze --fatal-infos
- name: Run Flutter tests
run: flutter test --reporter expanded test packages/cutdex_ui/test packages/cutdex_native/test
- name: Test update and release tools
run: |
python -m unittest discover -s tool/gitea -p 'test_*.py'
if ($LASTEXITCODE -ne 0) { throw 'Release tooling tests failed.' }
python -m unittest discover -s tool/windows -p '*_unit.py'
if ($LASTEXITCODE -ne 0) { throw 'Update tooling tests failed.' }
android:
name: Build Android APK
needs: quality
runs-on: cutdex-windows-x64
env:
GITEA_ACTOR: lingjhf
CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }}
steps:
- name: Check out source
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Configure persistent build caches
run: ./tool/gitea/prepare-build-cache.ps1
- name: Verify Flutter version and configure Java
run: |
$version = flutter --version --machine | ConvertFrom-Json
if ($version.frameworkVersion -ne '3.47.5') { throw 'Flutter 3.47.5 required.' }
flutter config --jdk-dir=$env:JAVA_HOME
if ($LASTEXITCODE -ne 0) { throw 'Flutter JDK setup failed.' }
- name: Resolve locked Flutter dependencies
run: flutter pub get --enforce-lockfile
- name: Configure Gradle memory and build cache
run: | run: |
$file = 'android/gradle.properties' $file = 'android/gradle.properties'
$properties = [IO.File]::ReadAllText($file).Replace('-Xmx8G', '-Xmx3G').Replace('MaxMetaspaceSize=4G', 'MaxMetaspaceSize=768m') $properties = [IO.File]::ReadAllText($file).Replace('-Xmx8G', '-Xmx3G').Replace('MaxMetaspaceSize=4G', 'MaxMetaspaceSize=768m')
[IO.File]::WriteAllText($file, $properties + "`norg.gradle.workers.max=4`n") [IO.File]::WriteAllText($file, $properties + "`norg.gradle.workers.max=4`norg.gradle.caching=true`n")
- run: flutter build apk --release --flavor production --target-platform android-arm64,android-x64 - name: Build production Android APK
- name: Build Windows from the pinned Gitea native release run: flutter build apk --release --flavor production --target-platform android-arm64,android-x64
- name: Upload Android CI artifact
uses: ./.gitea/actions/upload-artifact
with:
name: cutdex-android-build
path: build/app/outputs/flutter-apk/app-production-release.apk
compression-level: 0
retention-days: 30
windows-build:
name: Build Windows x64 app
needs: quality
runs-on: cutdex-windows-x64
env:
GITEA_ACTOR: lingjhf
CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }}
steps:
- name: Check out source
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Configure persistent build caches
run: ./tool/gitea/prepare-build-cache.ps1
- name: Verify Flutter version
run: |
$version = flutter --version --machine | ConvertFrom-Json
if ($version.frameworkVersion -ne '3.47.5') { throw 'Flutter 3.47.5 required.' }
- name: Resolve locked Flutter dependencies
run: flutter pub get --enforce-lockfile
- name: Build production Windows app
run: | run: |
Remove-Item Env:CUTDEX_WINDOWS_PATH, Env:CUTDEX_WINDOWS_PACKAGE_PATH -ErrorAction SilentlyContinue Remove-Item Env:CUTDEX_WINDOWS_PATH, Env:CUTDEX_WINDOWS_PACKAGE_PATH -ErrorAction SilentlyContinue
flutter build windows --release --flavor production flutter build windows --release --flavor production
if ($LASTEXITCODE -ne 0) { throw 'Windows build failed.' } if ($LASTEXITCODE -ne 0) { throw 'Windows build failed.' }
- name: Prepare isolated packaging tools - name: Verify native SDK matches pinned packaging tools
run: | run: |
python -m venv .build/package-tools python tool/windows/windows_updates.py verify-sdk
if ($LASTEXITCODE -ne 0) { throw 'Packaging environment setup failed.' } if ($LASTEXITCODE -ne 0) { throw 'Windows native SDK version validation failed.' }
& ./.build/package-tools/Scripts/python.exe -m pip install pefile==2024.8.26 - name: Save Windows app for independent packaging retries
if ($LASTEXITCODE -ne 0) { throw 'Packaging dependency installation failed.' } uses: ./.gitea/actions/upload-artifact
- name: Package application with:
name: cutdex-windows-app
path: |
build/windows/x64/production/runner/Release/
!build/windows/x64/production/runner/Release/**/processing/**
!build/windows/x64/production/runner/Release/**/*.pdb
!build/windows/x64/production/runner/Release/**/*.lib
!build/windows/x64/production/runner/Release/**/*.exp
!build/windows/x64/production/runner/Release/**/dartjni.dll
compression-level: 1
retention-days: 30
windows:
name: Audit and package Windows x64
needs: windows-build
runs-on: cutdex-windows-x64
steps:
- name: Check out source
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Download saved Windows app
uses: https://github.com/actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: cutdex-windows-app
path: build/windows/x64/production/runner/Release/
- name: Configure user .NET installation
run: | run: |
& ./.build/package-tools/Scripts/python.exe tool/gitea/package-app.py $directory = Join-Path $env:LOCALAPPDATA 'Cutdex/ci-tools/dotnet'
- name: Upload Android and Windows packages [IO.Directory]::CreateDirectory($directory) | Out-Null
uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 "DOTNET_INSTALL_DIR=$directory" | Out-File -LiteralPath $env:GITHUB_ENV -Encoding utf8 -Append
"DOTNET_ROOT=$directory" | Out-File -LiteralPath $env:GITHUB_ENV -Encoding utf8 -Append
- name: Set up .NET SDK
uses: https://github.com/actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1
with:
dotnet-version: '10.0.x'
- name: Prepare pinned packaging tools
run: ./tool/gitea/prepare-package-tools.ps1
- name: Audit and package Windows release
run: |
& $env:PACKAGE_PYTHON tool/gitea/package-app.py --platform windows --vpk $env:VPK_PATH
if ($LASTEXITCODE -ne 0) { throw 'Windows packaging failed.' }
- name: Upload Windows CI artifact
uses: ./.gitea/actions/upload-artifact
with:
name: cutdex-windows-build
path: dist/*
compression-level: 0
retention-days: 30
build:
name: Assemble and validate CI artifacts
needs: [android, windows]
runs-on: cutdex-windows-x64
env:
GITEA_ACTOR: lingjhf
CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }}
steps:
- name: Check out source
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Download Android CI artifact
uses: https://github.com/actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: cutdex-android-build
path: build/app/outputs/flutter-apk/
- name: Download Windows CI artifact
uses: https://github.com/actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: cutdex-windows-build
path: .build/windows-packages/
- name: Validate packages and generate metadata
run: |
python tool/gitea/package-app.py --platform assemble --windows-packages .build/windows-packages
if ($LASTEXITCODE -ne 0) { throw 'Application artifact validation failed.' }
- name: Upload combined CI artifact
uses: ./.gitea/actions/upload-artifact
with: with:
name: cutdex-release-packages name: cutdex-release-packages
path: dist/* path: dist/*
if-no-files-found: error compression-level: 0
retention-days: 30
- name: Upload release verification metadata
uses: ./.gitea/actions/upload-artifact
with:
name: cutdex-release-metadata
path: .build/release-metadata/*
compression-level: 0
retention-days: 30 retention-days: 30
checks: checks:
name: Gitea CI passed name: Gitea CI passed
@@ -71,7 +227,8 @@ jobs:
needs: build needs: build
runs-on: cutdex-windows-x64 runs-on: cutdex-windows-x64
steps: steps:
- env: - name: Verify CI result
env:
RESULT: ${{ needs.build.result }} RESULT: ${{ needs.build.result }}
run: | run: |
if ($env:RESULT -ne 'success') { throw "App build: $env:RESULT" } if ($env:RESULT -ne 'success') { throw "App build: $env:RESULT" }
+110 -10
View File
@@ -13,21 +13,121 @@ permissions:
concurrency: concurrency:
group: cutdex-release group: cutdex-release
cancel-in-progress: false cancel-in-progress: false
defaults:
run:
shell: pwsh
env:
PYTHONUTF8: '1'
CUTDEX_GITEA_INTERNAL_URL: http://127.0.0.1:3000
GIT_CONFIG_COUNT: '2'
GIT_CONFIG_KEY_0: core.autocrlf
GIT_CONFIG_VALUE_0: 'false'
GIT_CONFIG_KEY_1: core.eol
GIT_CONFIG_VALUE_1: lf
RELEASE_TAG: ${{ gitea.event.inputs.tag || gitea.ref_name }}
GITEA_REPOSITORY: ${{ gitea.repository }}
jobs: jobs:
release: prepare:
name: Prepare draft Release
runs-on: cutdex-windows-x64 runs-on: cutdex-windows-x64
outputs:
sha: ${{ steps.draft.outputs.sha }}
release-id: ${{ steps.draft.outputs.release-id }}
ci-run-id: ${{ steps.draft.outputs.ci-run-id }}
artifact-id: ${{ steps.draft.outputs.artifact-id }}
android-artifact-id: ${{ steps.draft.outputs.android-artifact-id }}
windows-artifact-id: ${{ steps.draft.outputs.windows-artifact-id }}
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
steps: steps:
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - name: Check out release tag
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with: with:
ref: ${{ gitea.event.inputs.tag || gitea.ref_name }} ref: ${{ gitea.event.inputs.tag || gitea.ref_name }}
persist-credentials: false persist-credentials: false
- name: Publish validated Android and Windows packages github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
shell: pwsh - name: Select successful CI and prepare draft
env: id: draft
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_REPOSITORY: ${{ gitea.repository }}
RELEASE_TAG: ${{ gitea.event.inputs.tag || gitea.ref_name }}
run: | run: |
$env:GITEA_SHA = git rev-parse HEAD $env:GITEA_SHA = git rev-parse HEAD
python tool/gitea/promote-release.py if ($LASTEXITCODE -ne 0) { throw 'Release source resolution failed.' }
if ($LASTEXITCODE -ne 0) { throw 'Release promotion failed.' } python tool/gitea/stage-release.py prepare-ci
if ($LASTEXITCODE -ne 0) { throw 'CI selection or draft preparation failed.' }
android:
name: Upload Android to draft Release
needs: prepare
runs-on: cutdex-windows-x64
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_SHA: ${{ needs.prepare.outputs.sha }}
RELEASE_ID: ${{ needs.prepare.outputs.release-id }}
CI_RUN_ID: ${{ needs.prepare.outputs.ci-run-id }}
CI_ARTIFACT_ID: ${{ needs.prepare.outputs.android-artifact-id }}
steps:
- name: Check out release commit
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
ref: ${{ needs.prepare.outputs.sha }}
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Download Android CI artifact
run: |
python tool/gitea/stage-release.py fetch-android --path .build/android
if ($LASTEXITCODE -ne 0) { throw 'android CI artifact download failed.' }
- name: Upload Android packages to draft
run: |
python tool/gitea/stage-release.py android --path .build/android
if ($LASTEXITCODE -ne 0) { throw 'android draft upload failed.' }
windows:
name: Upload Windows to draft Release
needs: prepare
runs-on: cutdex-windows-x64
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_SHA: ${{ needs.prepare.outputs.sha }}
RELEASE_ID: ${{ needs.prepare.outputs.release-id }}
CI_RUN_ID: ${{ needs.prepare.outputs.ci-run-id }}
CI_ARTIFACT_ID: ${{ needs.prepare.outputs.windows-artifact-id }}
steps:
- name: Check out release commit
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
ref: ${{ needs.prepare.outputs.sha }}
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Download Windows CI artifact
run: |
python tool/gitea/stage-release.py fetch-windows --path .build/windows
if ($LASTEXITCODE -ne 0) { throw 'windows CI artifact download failed.' }
- name: Upload Windows packages to draft
run: |
python tool/gitea/stage-release.py windows --path .build/windows
if ($LASTEXITCODE -ne 0) { throw 'windows draft upload failed.' }
publish:
name: Verify and publish Release
needs: [prepare, android, windows]
runs-on: cutdex-windows-x64
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_SHA: ${{ needs.prepare.outputs.sha }}
RELEASE_ID: ${{ needs.prepare.outputs.release-id }}
CI_RUN_ID: ${{ needs.prepare.outputs.ci-run-id }}
CI_ARTIFACT_ID: ${{ needs.prepare.outputs.artifact-id }}
steps:
- name: Check out release commit
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
ref: ${{ needs.prepare.outputs.sha }}
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Download release verification metadata
run: |
python tool/gitea/stage-release.py fetch-release --path dist
if ($LASTEXITCODE -ne 0) { throw 'CI verification metadata validation failed.' }
- name: Verify attachments and publish Release
run: |
python tool/gitea/stage-release.py publish --path dist
if ($LASTEXITCODE -ne 0) { throw 'Release publication failed.' }
+81
View File
@@ -0,0 +1,81 @@
# Windows 更新与 Gitea 发布
Cutdex 使用 deskup 0.3.0 的 Gitea 更新源,下载、校验、安装和重启由
Velopack 1.2.161 完成。正式版构建固定使用公开仓库
`https://git.orangraph.com/lingjhf/cutdex`,包身份为 `Cutdex`,更新频道为
`win-x64`。正式版不读取开发更新源环境变量,也不包含 Gitea 访问令牌。
## 发布附件
每个正式 Gitea Release 同时包含:
| 附件 | 用途 |
| --- | --- |
| `Cutdex-win-x64-Setup.exe` | 新用户安装 |
| `Cutdex-win-x64-Portable.zip` | Velopack 便携发行包,可自动更新 |
| `Cutdex-<更新版本>-win-x64-full.nupkg` | 完整更新包 |
| `releases.win-x64.json` | Windows x64 更新索引 |
| `cutdex-<显示版本>-android.apk` | Android ARM64/x86_64 应用 |
| `windows-dependency-audit.json` | Windows 原生依赖审计 |
| `SHA256SUMS` / `release-manifest.json` | 附件哈希与版本、频道、包身份声明 |
CI 构建正常应用后,在临时目录组装 Windows 发行内容,排除构建符号、
不用的 JNI DLL 和独立分发的 processing worker。审计及暂存文件校验后,
使用固定版本的 `vpk` 生成安装、便携和更新产物。每次使用新的打包输出目录,
索引只引用本次 Release 的一个完整包;不生成增量包。
`tool/gitea/package-app.py --vpk <vpk.exe 或 vpk.dll>` 要求 `dist` 为空。
打包机需要 .NET(仅运行 vpk)与 `pefile`;用户电脑不需要 .NET 或 Python。
CI 安装 .NET 10 和 vpk 1.2.161。
发布工作流只提升**同一提交**成功的 main CI 产物。上传前校验完整附件集合、
版本、包身份、频道及索引指向的包哈希;上传至草稿 Release,重新读取所有
附件逐字节核对,并拒绝多余或过期附件,之后才发布。发布失败保留草稿,
同内容可重试;已发布版本不可覆盖。
## 版本与迁移
例如 `pubspec.yaml` 的 `0.1.1+2` 对应显示版本/标签 `0.1.1`/`v0.1.1`,
Velopack 更新版本为 `0.1.1-build.2`。数字构建号参与更新版本排序,
避免 SemVer `+2` 不参与排序的问题。Windows 可执行文件版本必须与 pubspec
一致;每次正式发布提升应用版本与构建号,勿复用已发布标签。
旧的普通 `cutdex-<版本>-windows-x64.zip` 不含 Velopack 安装元数据,不能
直接获得自动更新。旧用户需要先使用新的 Setup.exe 安装,或解压新的
Velopack Portable ZIP;之后由应用内更新完成升级。
Gitea SDK 查询最近 10 个 Release,跳过标为预发布的 Release,并读取对应
频道索引。需要保持最新正式 Windows Release 在这个查询窗口中。
索引遗漏或损坏可能被 SDK 跳过并表现为没有更新,因此发布流程必须保证
附件完整。仓库及附件必须可匿名下载,Gitea 服务的 API 应位于 `/api/v1`。
## 开发与验证
development 包身份为 `Cutdex.Dev`,默认不配置更新源。
更新策略通过 Dart 的 `WindowsUpdateConfiguration` 传入,不再使用 CMake
更新源变量。正式版固定选用正式 Gitea 仓库,保留 `Cutdex` 注册表偏好命名空间;
安装时显式传入静默和自动重启选项。
开发更新源通过编译期 Dart defines 配置,修改后需重新构建。例如本地测试:
```powershell
flutter build windows --release --flavor development `
--dart-define=CUTDEX_WINDOWS_UPDATE_SOURCE=web `
--dart-define=CUTDEX_WINDOWS_UPDATE_URL=http://127.0.0.1:8765 `
--dart-define=CUTDEX_UPDATE_TEST_HTTP=true
```
Gitea 开发仓库使用 `CUTDEX_WINDOWS_UPDATE_SOURCE=gitea` 和仓库 URL。
仅设置进程环境变量不会配置 Dart 更新源。正式版忽略开发 defines。
原生 SDK 离线缓存仍通过 `DESKUP_VELOPACK_ARCHIVE` 环境变量指定。
```powershell
python -m unittest discover -s tool/gitea -p 'test_*.py'
python -m unittest discover -s tool/windows -p '*_unit.py'
python tool/windows/test_windows_updates.py --vpk <vpk.exe 或 vpk.dll> --offline
```
本地更新测试会构建两版独立测试应用,验证损坏包拒绝、重新下载、安装和
重启;不修改运行中的开发应用,也不上传真实 Release。正式发布前还应在
独立 Windows 环境验证应用持久化与安装/便携两种分发方式。Android 签名与
processing worker 独立分发策略沿用现有流水线。
+7 -2
View File
@@ -1,6 +1,7 @@
import 'dart:async'; import 'dart:async';
import '../diagnostics/app_diagnostics.dart'; import '../diagnostics/app_diagnostics.dart';
import 'app_update_configuration.dart';
import 'package:deskup/deskup.dart'; import 'package:deskup/deskup.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
@@ -26,7 +27,11 @@ AppUpdateBridge appUpdateBridge(Ref ref) {
// Application adapter: Riverpod ownership and the macOS workspace quit gate. // Application adapter: Riverpod ownership and the macOS workspace quit gate.
class AppUpdateBridge { class AppUpdateBridge {
AppUpdateBridge([MethodChannel channel = appUpdatesChannel]) AppUpdateBridge([MethodChannel channel = appUpdatesChannel])
: _updater = Deskup(channel: channel); : _updater = Deskup(
channel: channel,
windows: windowsUpdateConfiguration(),
macos: macosUpdateConfiguration(),
);
final Deskup _updater; final Deskup _updater;
Stream<UpdateStatus> get events => _updater.events; Stream<UpdateStatus> get events => _updater.events;
@@ -65,7 +70,7 @@ class AppUpdateBridge {
Future<void> check() => _updater.check(); Future<void> check() => _updater.check();
Future<void> download() => _updater.download(); Future<void> download() => _updater.download();
Future<void> validateInstall() => _updater.validateInstall(); Future<void> validateInstall() => _updater.validateInstall();
Future<void> install() => _updater.install(); Future<void> install() => _updater.install(silent: true, restart: true);
Future<void> setAutomaticChecks(bool enabled) => Future<void> setAutomaticChecks(bool enabled) =>
_updater.setAutomaticChecks(enabled); _updater.setAutomaticChecks(enabled);
@@ -0,0 +1,48 @@
import 'package:deskup/deskup.dart';
import 'package:flutter/services.dart';
// Values are compiled from Dart defines; process environment does not redirect production.
MacOSUpdateConfiguration macosUpdateConfiguration() =>
const MacOSUpdateConfiguration(
allowLocalHttp:
appFlavor == 'development' &&
bool.fromEnvironment('CUTDEX_UPDATE_TEST_HTTP'),
);
WindowsUpdateConfiguration? windowsUpdateConfiguration({
String? flavor,
String developmentUrl = const String.fromEnvironment(
'CUTDEX_WINDOWS_UPDATE_URL',
),
String developmentSource = const String.fromEnvironment(
'CUTDEX_WINDOWS_UPDATE_SOURCE',
defaultValue: 'gitea',
),
bool allowLocalHttp = const bool.fromEnvironment('CUTDEX_UPDATE_TEST_HTTP'),
}) {
final development = (flavor ?? appFlavor) == 'development';
if (development && developmentUrl.isEmpty) return null;
final WindowsUpdateSource source;
if (!development) {
source = GiteaUpdateSource(
repositoryUrl: Uri.parse('https://git.orangraph.com/lingjhf/cutdex'),
);
} else if (developmentSource == 'gitea') {
source = GiteaUpdateSource(
repositoryUrl: Uri.parse(developmentUrl),
allowLocalHttp: allowLocalHttp,
);
} else if (developmentSource == 'web') {
source = WebUpdateSource(
url: Uri.parse(developmentUrl),
allowLocalHttp: allowLocalHttp,
);
} else {
throw ArgumentError.value(developmentSource, 'developmentSource');
}
return WindowsUpdateConfiguration(
source: source,
expectedPackageId: development ? 'Cutdex.Dev' : 'Cutdex',
preferenceNamespace: 'Cutdex',
);
}
+6 -5
View File
@@ -302,11 +302,12 @@ packages:
deskup: deskup:
dependency: "direct main" dependency: "direct main"
description: description:
name: deskup path: "."
sha256: "5a7fb021ba3207e5a85d440d378832156896d2eea616838ad21547aa0af68df1" ref: ccbeb02ed1bbf6b4388981a0e641aff7404637bd
url: "https://pub.dev" resolved-ref: ccbeb02ed1bbf6b4388981a0e641aff7404637bd
source: hosted url: "https://github.com/lingjhf/deskup.git"
version: "0.1.0" source: git
version: "0.3.0"
drift: drift:
dependency: "direct main" dependency: "direct main"
description: description:
+5 -2
View File
@@ -5,7 +5,7 @@ publish_to: none
version: 0.1.1+2 version: 0.1.1+2
environment: environment:
sdk: ^3.13.2 sdk: ^3.13.4
workspace: workspace:
- packages/* - packages/*
@@ -13,7 +13,10 @@ workspace:
dependencies: dependencies:
cutdex_ui: ^0.1.0 cutdex_ui: ^0.1.0
cutdex_native: ^0.1.0 cutdex_native: ^0.1.0
deskup: ^0.1.0 deskup:
git:
url: https://github.com/lingjhf/deskup.git
ref: ccbeb02ed1bbf6b4388981a0e641aff7404637bd
flutter: flutter:
sdk: flutter sdk: flutter
+30
View File
@@ -0,0 +1,30 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:cutdex/integrations/app_update_configuration.dart';
void main() {
test('production ignores development source overrides', () {
final config = windowsUpdateConfiguration(
flavor: 'production',
developmentUrl: 'http://127.0.0.1:8765',
developmentSource: 'web',
allowLocalHttp: true,
)!;
final map = config.toMap();
expect(
(map['source'] as Map)['url'],
'https://git.orangraph.com/lingjhf/cutdex',
);
expect(map['expectedPackageId'], 'Cutdex');
});
test('development requires opt-in and uses an isolated identity', () {
expect(windowsUpdateConfiguration(flavor: 'development'), isNull);
final map = windowsUpdateConfiguration(
flavor: 'development',
developmentUrl: 'http://127.0.0.1:8765',
developmentSource: 'web',
allowLocalHttp: true,
)!.toMap();
expect(map['expectedPackageId'], 'Cutdex.Dev');
expect((map['source'] as Map)['type'], 'web');
});
}
+3 -2
View File
@@ -126,9 +126,10 @@ void main() {
.closeSource(); .closeSource();
} }
await access.dispose(); await access.dispose();
// UI/provider disposal owns the project; allow its async cleanup to finish. // Provider disposal starts async cleanup without waiting for it. Close the
// workspace explicitly before deleting files, especially on Windows.
await container.read(projectsProvider.notifier).prepareToQuit();
container.dispose(); container.dispose();
await Future<void>.delayed(const Duration(milliseconds: 50));
await root.delete(recursive: true); await root.delete(recursive: true);
messenger.setMockMethodCallHandler(native, null); messenger.setMockMethodCallHandler(native, null);
messenger.setMockMethodCallHandler(events, null); messenger.setMockMethodCallHandler(events, null);
+3 -1
View File
@@ -64,7 +64,7 @@ python tool/windows/package_windows_release.py `
## 应用更新产物 ## 应用更新产物
Cutdex 的更新构建配置为 macOS 的 `CUTDEX_UPDATE_FEED_URL` / `CUTDEX_UPDATE_PUBLIC_KEY`,Windows 的 `CUTDEX_WINDOWS_UPDATE_URL`;在构建前设置正式 HTTPS 更新源。 Cutdex 的 macOS 更新构建配置为 `CUTDEX_UPDATE_FEED_URL` / `CUTDEX_UPDATE_PUBLIC_KEY`;在构建前设置正式 HTTPS 更新源。Windows production 使用固定的公开 Gitea 仓库与 deskup 0.2.0;开发更新源、Release 附件与迁移说明见 [Windows 更新与发布](../docs/windows-updates.md)。
生成更新产物的应用入口: 生成更新产物的应用入口:
@@ -75,6 +75,8 @@ python3 tool/windows/windows_updates.py pack --help
提升应用构建号,保留当前线上更新索引供版本检查;development 与 production 使用独立发布目录。脚本只生成产物,不上传。完整升级模拟使用各平台的 `test_*_updates.py`,参数见 `--help`,测试包不用于分发。 提升应用构建号,保留当前线上更新索引供版本检查;development 与 production 使用独立发布目录。脚本只生成产物,不上传。完整升级模拟使用各平台的 `test_*_updates.py`,参数见 `--help`,测试包不用于分发。
deskup 0.3.0 的开发更新源由 Dart 参数配置。Windows 的编译期配置示例见 [Windows 更新文档](../docs/windows-updates.md)。macOS 本地 HTTP 更新测试的源应用需使用 `--flavor development --dart-define=CUTDEX_UPDATE_TEST_HTTP=true` 构建,再运行 `test_macos_updates.py`;签名公钥和 appcast 仍由打包工具写入应用 Info.plist。
## 诊断与共享测试入口 ## 诊断与共享测试入口
- `diagnostics/frame_budget.py`:读取 `CUTDEX_FRAME_TIMINGS` JSONL,可带阶段标记文件;报告帧耗时。 - `diagnostics/frame_budget.py`:读取 `CUTDEX_FRAME_TIMINGS` JSONL,可带阶段标记文件;报告帧耗时。
+1
View File
@@ -38,6 +38,7 @@ def main():
('tool/tests', '*_test.py'), ('tool/tests', '*_test.py'),
('tool/windows', 'test_check_windows_release.py'), ('tool/windows', 'test_check_windows_release.py'),
('tool/windows', '*_unit.py'), ('tool/windows', '*_unit.py'),
('tool/gitea', 'test_*.py'),
]: ]:
run([python, '-m', 'unittest', 'discover', '-s', directory, '-p', pattern]) run([python, '-m', 'unittest', 'discover', '-s', directory, '-p', pattern])
flutter = os.environ.get('FLUTTER') or shutil.which('flutter') flutter = os.environ.get('FLUTTER') or shutil.which('flutter')
+85 -26
View File
@@ -1,23 +1,19 @@
"""Package the Windows Release directory and Android production APK.""" """Package Android and audited Velopack Windows installation/update artifacts."""
import argparse
import hashlib import hashlib
import json import json
from pathlib import Path from pathlib import Path
import re
import shutil import shutil
import sys import sys
import tempfile
import zipfile import zipfile
from release_artifacts import AUDIT, FEED, INSTALLER, PORTABLE, METADATA, app_versions, checksum_lines, validate_artifact
ROOT = Path(__file__).resolve().parents[2] ROOT = Path(__file__).resolve().parents[2]
def main(): def validate_apk(apk):
version = re.search(r'^version: (\S+)', (ROOT / 'pubspec.yaml').read_text(), re.M)[1].split('+')[0]
output = ROOT / 'dist'
output.mkdir(exist_ok=True)
apk = ROOT / 'build/app/outputs/flutter-apk/app-production-release.apk'
windows = ROOT / 'build/windows/x64/production/runner/Release'
if not apk.is_file() or not (windows / 'cutdex.exe').is_file():
raise ValueError('Both production builds are required')
with zipfile.ZipFile(apk) as archive: with zipfile.ZipFile(apk) as archive:
names = archive.namelist() names = archive.namelist()
for abi in ('arm64-v8a', 'x86_64'): for abi in ('arm64-v8a', 'x86_64'):
@@ -25,24 +21,87 @@ def main():
raise ValueError(f'APK missing Flutter ABI: {abi}') raise ValueError(f'APK missing Flutter ABI: {abi}')
if any(name.startswith('lib/armeabi-v7a/') for name in names): if any(name.startswith('lib/armeabi-v7a/') for name in names):
raise ValueError('APK must use supported 64-bit ABIs only') raise ValueError('APK must use supported 64-bit ABIs only')
shutil.copyfile(apk, output / f'cutdex-{version}-android.apk')
def package_windows(windows, vpk, windows_version):
sys.path.insert(0, str(ROOT / 'tool/windows')) sys.path.insert(0, str(ROOT / 'tool/windows'))
from check_windows_release import audit from check_windows_release import audit
unused_jni = windows / 'dartjni.dll' from windows_updates import package_app
if unused_jni.exists(): with tempfile.TemporaryDirectory(prefix='cutdex-release-') as directory:
unused_jni.unlink() temporary = Path(directory)
report = audit(windows, require_processing=False) staged, releases = temporary / 'app', temporary / 'releases'
(output / 'windows-dependency-audit.json').write_text(json.dumps(report, indent=2) + '\n') shutil.copytree(windows, staged,
package = output / f'cutdex-{version}-windows-x64.zip' ignore=shutil.ignore_patterns('processing', '*.pdb', '*.lib', '*.exp', 'dartjni.dll'))
with zipfile.ZipFile(package, 'w', compression=zipfile.ZIP_DEFLATED) as archive: report = audit(staged, require_processing=False)
for path in sorted(windows.rglob('*')): checksums = {}
if path.is_file() and path.suffix.lower() not in ('.pdb', '.lib', '.exp'): for path in sorted(staged.rglob('*')):
archive.write(path, f'cutdex-{version}/' + path.relative_to(windows).as_posix()) if path.is_file():
files = sorted(output.glob('*.apk')) + sorted(output.glob('*.zip')) with path.open('rb') as stream:
manifest = {path.name: hashlib.file_digest(path.open('rb'), 'sha256').hexdigest() for path in files} checksums[path.relative_to(staged).as_posix()] = hashlib.file_digest(stream, 'sha256').hexdigest()
(output / 'SHA256SUMS').write_text(''.join(f'{digest} {name}\n' for name, digest in manifest.items())) (staged / 'checksums.json').write_text(json.dumps(checksums), encoding='utf-8')
(output / 'release-manifest.json').write_text(json.dumps({'version': version, 'files': manifest, 'androidSigning': 'debug', 'processingWorkersBundled': False}, indent=2) + '\n') result = package_app(staged, releases, vpk, require_processing=False)
print(json.dumps(manifest, indent=2)) if result['version'] != windows_version:
raise ValueError('Built Windows version differs from pubspec')
contents = {AUDIT: (json.dumps(report, indent=2) + '\n').encode()}
for path in releases.iterdir():
if path.name in {FEED, INSTALLER, PORTABLE} or path.suffix == '.nupkg':
contents[path.name] = path.read_bytes()
return contents
def assemble(contents, version, windows_version):
files = {name: hashlib.sha256(body).hexdigest() for name, body in contents.items()}
manifest = {'version': version, 'files': files, 'windowsUpdateVersion': windows_version,
'windowsPackageId': 'Cutdex', 'windowsChannel': 'win-x64',
'androidSigning': 'debug', 'processingWorkersBundled': False}
contents['SHA256SUMS'] = checksum_lines(files).encode()
contents['release-manifest.json'] = (json.dumps(manifest, indent=2) + '\n').encode()
validate_artifact(contents, version, windows_version)
return contents
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--platform', choices=['all', 'windows', 'assemble'], default='all')
parser.add_argument('--vpk', type=Path, help='Pinned vpk executable or DLL')
parser.add_argument('--windows-packages', type=Path, help='Previously packaged Windows artifact directory')
args = parser.parse_args()
if args.platform != 'assemble' and args.vpk is None:
parser.error('--vpk is required when packaging Windows')
if args.platform == 'assemble' and args.windows_packages is None:
parser.error('--windows-packages is required when assembling artifacts')
version, windows_version = app_versions(ROOT / 'pubspec.yaml')
output = ROOT / 'dist'
if output.exists() and any(output.iterdir()):
raise ValueError('dist must be empty; use a clean release workspace')
metadata = ROOT / '.build/release-metadata'
if args.platform != 'windows' and metadata.exists() and any(metadata.iterdir()):
raise ValueError('Release metadata output must be empty')
apk = ROOT / 'build/app/outputs/flutter-apk/app-production-release.apk'
windows = ROOT / 'build/windows/x64/production/runner/Release'
if args.platform != 'windows':
validate_apk(apk)
if args.platform == 'assemble':
contents = {path.name: path.read_bytes() for path in args.windows_packages.iterdir() if path.is_file()}
if any(path.is_dir() for path in args.windows_packages.iterdir()):
raise ValueError('Windows packages must be a flat artifact directory')
if f'cutdex-{version}-android.apk' in contents:
raise ValueError('Unexpected Android package in Windows artifact')
else:
if not (windows / 'cutdex.exe').is_file():
raise ValueError('Production Windows build is required')
contents = package_windows(windows, args.vpk, windows_version)
if args.platform != 'windows':
contents[f'cutdex-{version}-android.apk'] = apk.read_bytes()
assemble(contents, version, windows_version)
output.mkdir(exist_ok=True)
for name, body in contents.items():
(output / name).write_bytes(body)
if args.platform != 'windows':
metadata.mkdir(parents=True, exist_ok=True)
for name in METADATA:
(metadata / name).write_bytes(contents[name])
print(json.dumps({'platform': args.platform, 'version': version, 'files': sorted(contents)}, indent=2))
if __name__ == '__main__': if __name__ == '__main__':
+14
View File
@@ -0,0 +1,14 @@
$ErrorActionPreference = 'Stop'
# Use runner-user caches rather than checkout-local directories. Preserve any
# administrator overrides, and do not archive caches while another job uses them.
$pubCache = if ($env:PUB_CACHE) { $env:PUB_CACHE } else { Join-Path $env:LOCALAPPDATA 'Pub/Cache' }
$gradleCache = if ($env:GRADLE_USER_HOME) { $env:GRADLE_USER_HOME } else { Join-Path $env:USERPROFILE '.gradle' }
foreach ($directory in @($pubCache, $gradleCache)) {
[IO.Directory]::CreateDirectory($directory) | Out-Null
}
if ($env:GITHUB_ENV) {
"PUB_CACHE=$pubCache" | Out-File -LiteralPath $env:GITHUB_ENV -Encoding utf8 -Append
"GRADLE_USER_HOME=$gradleCache" | Out-File -LiteralPath $env:GITHUB_ENV -Encoding utf8 -Append
}
Write-Output "Persistent Pub cache: $pubCache"
Write-Output "Persistent Gradle cache: $gradleCache"
+40
View File
@@ -0,0 +1,40 @@
$ErrorActionPreference = 'Stop'
# Persist fixed-version tools outside checkout, which Actions cleans between jobs.
$identity = python -c "import hashlib, sys; print(hashlib.sha256((sys.executable + sys.version).encode()).hexdigest()[:16])"
if ($LASTEXITCODE -ne 0) { throw 'Cannot identify packaging Python.' }
$root = Join-Path $env:LOCALAPPDATA "Cutdex/ci-tools/python-$identity-pefile-2024.8.26-vpk-1.2.161"
$python = Join-Path $root 'python/Scripts/python.exe'
$vpk = Join-Path $root 'vpk/vpk.exe'
$mutex = [Threading.Mutex]::new($false, "Local\CutdexPackageTools-$identity")
$locked = $false
try {
try { $locked = $mutex.WaitOne([TimeSpan]::FromMinutes(10)) }
catch [Threading.AbandonedMutexException] { $locked = $true }
if (-not $locked) { throw 'Timed out waiting for packaging tools setup.' }
if (-not (Test-Path -LiteralPath $python)) {
python -m venv (Join-Path $root 'python')
if ($LASTEXITCODE -ne 0) { throw 'Packaging environment setup failed.' }
}
$pefileVersion = & $python -c "import importlib.metadata; print(next((d.version for d in importlib.metadata.distributions() if d.metadata['Name'].lower() == 'pefile'), 'missing'))"
if ($LASTEXITCODE -ne 0) { throw 'Cached packaging Python failed.' }
if ($pefileVersion -ne '2024.8.26') {
& $python -m pip install pefile==2024.8.26
if ($LASTEXITCODE -ne 0) { throw 'Packaging dependency installation failed.' }
}
if (-not (Test-Path -LiteralPath $vpk)) {
dotnet tool install vpk --version 1.2.161 --tool-path (Join-Path $root 'vpk')
if ($LASTEXITCODE -ne 0) { throw 'Velopack tool installation failed.' }
}
$help = & $vpk --legacyConsole --skip-updates --help 2>&1
if ($LASTEXITCODE -ne 0 -or ($help -join "`n") -notmatch '(?<![\d.])1\.2\.161(?![\d.])') {
throw 'Cached Velopack version validation failed.'
}
if ($env:GITHUB_ENV) {
"PACKAGE_PYTHON=$python" | Out-File -LiteralPath $env:GITHUB_ENV -Encoding utf8 -Append
"VPK_PATH=$vpk" | Out-File -LiteralPath $env:GITHUB_ENV -Encoding utf8 -Append
}
Write-Output "Packaging tools ready: $root"
} finally {
if ($locked) { $mutex.ReleaseMutex() }
$mutex.Dispose()
}
-94
View File
@@ -1,94 +0,0 @@
"""Promote packages from a successful main CI for the exact release commit."""
import hashlib
import io
import json
import os
from pathlib import Path
import re
import urllib.error
import urllib.parse
import urllib.request
import uuid
import zipfile
SERVER = 'https://git.orangraph.com'
REPO = os.environ['GITEA_REPOSITORY']
TOKEN = os.environ['GITEA_TOKEN']
BASE = f'{SERVER}/api/v1/repos/{REPO}'
def request(url, data=None, method=None, content_type='application/json'):
headers = {'Authorization': f'token {TOKEN}'}
if data is not None:
headers['Content-Type'] = content_type
if isinstance(data, dict):
data = json.dumps(data).encode()
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=300) as response:
body = response.read()
return json.loads(body) if 'application/json' in response.headers.get('Content-Type', '') else body
def download(asset):
url = urllib.parse.urlparse(asset['browser_download_url'])
if url.hostname != 'git.orangraph.com':
raise ValueError('Unexpected attachment host')
return request(urllib.parse.urlunparse(url._replace(scheme='https', netloc='git.orangraph.com')))
def main():
sha = os.environ['GITEA_SHA']
tag = os.environ['RELEASE_TAG']
version = re.search(r'^version: (\S+)', Path('pubspec.yaml').read_text(), re.M)[1].split('+')[0]
if tag != f'v{version}':
raise ValueError('Release tag must match pubspec version')
runs = request(f'{BASE}/actions/runs?limit=100')['workflow_runs']
matches = [run for run in runs if run['head_sha'] == sha and run['path'].endswith('@refs/heads/main') and run['conclusion'] == 'success' and Path(run['path'].split('@')[0]).name == 'ci.yml']
if not matches:
raise ValueError('No successful main CI for this exact commit; run CI before releasing')
run = max(matches, key=lambda item: item['id'])
artifacts = request(f"{BASE}/actions/runs/{run['id']}/artifacts")['artifacts']
found = [item for item in artifacts if item['name'] == 'cutdex-release-packages' and not item.get('expired', False)]
if len(found) != 1:
raise ValueError('Expected one validated application artifact')
data = request(f"{BASE}/actions/artifacts/{found[0]['id']}/zip")
with zipfile.ZipFile(io.BytesIO(data)) as archive:
contents = {item.filename: archive.read(item) for item in archive.infolist() if not item.is_dir()}
manifest = json.loads(contents['release-manifest.json'])
if manifest['version'] != version:
raise ValueError('Artifact version does not match release')
expected = {f'cutdex-{version}-android.apk', f'cutdex-{version}-windows-x64.zip'}
if set(manifest['files']) != expected:
raise ValueError('Release requires both Android and Windows packages')
for name, digest in manifest['files'].items():
if hashlib.sha256(contents[name]).hexdigest() != digest:
raise ValueError(f'Package checksum mismatch: {name}')
releases = request(f'{BASE}/releases?limit=100')
existing = [release for release in releases if release['tag_name'] == tag]
if existing:
release = existing[0]
if not release['draft']:
raise ValueError('Release already published; choose a new version')
else:
release = request(f'{BASE}/releases', {'tag_name': tag, 'target_commitish': sha, 'name': f'Cutdex {version}', 'draft': True, 'body': f'Windows x64 portable ZIP and Android ARM64/x86_64 APK. Android currently uses the project debug signing key. Processing workers and models are distributed separately. Verified CI run: {run["id"]}.'}, 'POST')
assets = request(f"{BASE}/releases/{release['id']}/assets")
for name, body in contents.items():
if '/' in name or '\\' in name:
raise ValueError('Unexpected artifact path')
prior = [asset for asset in assets if asset['name'] == name]
if prior:
downloaded = download(prior[0])
if downloaded != body:
raise ValueError(f'Refusing to replace Release asset: {name}')
continue
boundary = uuid.uuid4().hex
payload = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{name}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode() + body + f'\r\n--{boundary}--\r\n'.encode())
asset = request(f"{BASE}/releases/{release['id']}/assets?name={urllib.parse.quote(name)}", payload, 'POST', f'multipart/form-data; boundary={boundary}')
if download(asset) != body:
raise ValueError(f'Remote checksum verification failed: {name}')
request(f"{BASE}/releases/{release['id']}", {'draft': False}, 'PATCH')
print(f'{SERVER}/{REPO}/releases/tag/{tag}')
if __name__ == '__main__':
main()
+80
View File
@@ -0,0 +1,80 @@
"""Validate the complete app artifact before creating or publishing a Release."""
import hashlib
import json
from pathlib import Path
import re
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'windows'))
from update_versions import update_version
FEED = 'releases.win-x64.json'
INSTALLER = 'Cutdex-win-x64-Setup.exe'
PORTABLE = 'Cutdex-win-x64-Portable.zip'
AUDIT = 'windows-dependency-audit.json'
METADATA = frozenset({'release-manifest.json', 'SHA256SUMS', FEED, AUDIT})
def app_versions(pubspec):
match = re.search(r'^version:\s*(\d+\.\d+\.\d+)\+(\d+)\s*$',
Path(pubspec).read_text(encoding='utf-8'), re.M)
if not match:
raise ValueError('Application version must include a numeric build number')
return match[1], update_version(match[1], match[2])
def checksum_lines(files):
return ''.join(f'{files[name]} {name}\n' for name in sorted(files))
def validate_metadata(contents, version, windows_version):
if set(contents) != METADATA:
raise ValueError('Release metadata requires manifest, checksums, index and audit')
manifest = json.loads(contents['release-manifest.json'])
if (manifest['version'] != version or manifest.get('windowsUpdateVersion') != windows_version
or manifest.get('windowsPackageId') != 'Cutdex'
or manifest.get('windowsChannel') != 'win-x64'):
raise ValueError('Artifact version, identity or channel does not match release')
feed = json.loads(contents[FEED])
assets = feed.get('Assets', [])
if len(assets) != 1:
raise ValueError('Release index must contain exactly one complete full package')
asset = assets[0]
if (asset.get('PackageId') != 'Cutdex' or asset.get('Version') != windows_version
or asset.get('Type') != 'Full'):
raise ValueError('Update package identity, version or type does not match release')
package = asset.get('FileName', '')
if not re.fullmatch(r'[A-Za-z0-9_.-]+\.nupkg', package):
raise ValueError('Invalid update package filename')
expected = {f'cutdex-{version}-android.apk', INSTALLER, PORTABLE, FEED, AUDIT, package}
if set(manifest['files']) != expected:
raise ValueError('Release requires APK, installer, Portable ZIP, index, full package and audit')
for name, digest in manifest['files'].items():
if not isinstance(digest, str) or not re.fullmatch(r'[0-9a-f]{64}', digest):
raise ValueError('Invalid package checksum: ' + name)
if name in contents and hashlib.sha256(contents[name]).hexdigest() != digest:
raise ValueError(f'Package checksum mismatch: {name}')
if (not isinstance(asset.get('Size'), int) or asset['Size'] < 0
or str(asset.get('SHA256', '')).lower() != manifest['files'][package]
or not re.fullmatch(r'[0-9a-fA-F]{40}', str(asset.get('SHA1', '')))):
raise ValueError('Update index checksums do not match the full package')
if contents['SHA256SUMS'].decode('utf-8') != checksum_lines(manifest['files']):
raise ValueError('SHA256SUMS differs from the release manifest')
return manifest
def validate_artifact(contents, version, windows_version):
manifest = validate_metadata({name: contents[name] for name in METADATA}, version, windows_version)
if set(contents) != set(manifest['files']) | {'SHA256SUMS', 'release-manifest.json'}:
raise ValueError('Release requires APK, installer, Portable ZIP, index, full package and audit')
for name, digest in manifest['files'].items():
if hashlib.sha256(contents[name]).hexdigest() != digest:
raise ValueError(f'Package checksum mismatch: {name}')
asset = json.loads(contents[FEED])['Assets'][0]
package = asset['FileName']
payload = contents[package]
if (asset.get('Size') != len(payload)
or str(asset.get('SHA256', '')).lower() != hashlib.sha256(payload).hexdigest()
or str(asset.get('SHA1', '')).lower() != hashlib.sha1(payload).hexdigest()):
raise ValueError('Update index checksums do not match the full package')
return manifest
+135
View File
@@ -0,0 +1,135 @@
"""Gitea HTTP and bounded transfer helpers for staged release publication."""
import hashlib
from concurrent.futures import ThreadPoolExecutor
import http.client
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
SERVER = 'https://git.orangraph.com'
RETRY_DELAYS = (5, 15)
def transport_url(url):
"""Route this host's Gitea traffic locally when the runner opts in."""
internal = os.environ.get('CUTDEX_GITEA_INTERNAL_URL', '').rstrip('/')
if not internal:
return url
if internal != 'http://127.0.0.1:3000':
raise ValueError('Unexpected internal Gitea endpoint')
parsed = urllib.parse.urlparse(url)
if parsed.scheme != 'https' or parsed.netloc != 'git.orangraph.com':
raise ValueError('Unexpected Gitea transport origin')
return urllib.parse.urlunparse(parsed._replace(scheme='http', netloc='127.0.0.1:3000'))
def transient(error):
if isinstance(error, urllib.error.HTTPError):
if error.code == 404 and error.headers.get('Content-Type', '').split(';')[0].lower() == 'text/html':
body = error.read(64 * 1024).lower()
# FRP returns this page while the vhost tunnel is unavailable.
# A normal Gitea API 404 remains a permanent error.
return b'github.com/fatedier/frp' in body and b'not found' in body
return error.code in {408, 429, 500, 502, 503, 504}
return isinstance(error, (urllib.error.URLError, TimeoutError, ConnectionError,
http.client.IncompleteRead))
def retry_read(operation):
"""Retry safe attachment-list reads, without retrying permanent HTTP errors."""
for attempt in range(len(RETRY_DELAYS) + 1):
try:
return operation()
except Exception as error:
if not transient(error) or attempt == len(RETRY_DELAYS):
raise
print(f'Attachment list temporarily unavailable; retrying in {RETRY_DELAYS[attempt]}s.', file=sys.stderr)
time.sleep(RETRY_DELAYS[attempt])
def request(url, data=None, method=None, content_type='application/json'):
endpoint = transport_url(url)
headers = {'Authorization': 'token ' + os.environ['GITEA_TOKEN']}
if endpoint != url:
# Gitea constructs response links from Host, even when reached locally.
headers['Host'] = 'git.orangraph.com'
if data is not None:
headers['Content-Type'] = content_type
if isinstance(data, dict):
data = json.dumps(data).encode()
req = urllib.request.Request(endpoint, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=300) as response:
body = response.read()
return json.loads(body) if body and 'application/json' in response.headers.get('Content-Type', '') else body
def attachment_url(asset):
url = urllib.parse.urlparse(asset['browser_download_url'])
if url.hostname != 'git.orangraph.com':
raise ValueError('Unexpected attachment host')
return urllib.parse.urlunparse(url._replace(scheme='https', netloc='git.orangraph.com'))
def fingerprint(asset):
"""Hash one remote attachment in chunks, keeping memory usage bounded."""
sha256, sha1, size = hashlib.sha256(), hashlib.sha1(), 0
url = attachment_url(asset)
endpoint = transport_url(url)
headers = {'Authorization': 'token ' + os.environ['GITEA_TOKEN']}
if endpoint != url:
headers['Host'] = 'git.orangraph.com'
req = urllib.request.Request(endpoint, headers=headers)
with urllib.request.urlopen(req, timeout=300) as response:
while chunk := response.read(1024 * 1024):
sha256.update(chunk)
sha1.update(chunk)
size += len(chunk)
return {'sha256': sha256.hexdigest(), 'sha1': sha1.hexdigest(), 'size': size}
def upload_contents(base, release_id, contents, *, transport=None):
send = transport or request
def attachment_names():
assets = retry_read(lambda: send(f"{base}/releases/{release_id}/assets"))
names = [asset['name'] for asset in assets]
if len(set(names)) != len(names):
raise ValueError('Duplicate Release attachments')
return set(names)
names = attachment_names()
for name in contents:
if '/' in name or '\\' in name:
raise ValueError('Unexpected artifact path')
def upload(item):
name, body = item
boundary = uuid.uuid4().hex
payload = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{name}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode() + body + f'\r\n--{boundary}--\r\n'.encode())
for attempt in range(len(RETRY_DELAYS) + 1):
# A timeout can occur after Gitea has committed the upload. Reconcile
# before another POST; publication will still verify the file bytes.
if attempt and name in attachment_names():
return
try:
send(f"{base}/releases/{release_id}/assets?name={urllib.parse.quote(name)}", payload, 'POST', f'multipart/form-data; boundary={boundary}')
return
except Exception as error:
if not transient(error):
raise
if attempt == len(RETRY_DELAYS):
if name in attachment_names():
return
raise
print(f'Upload temporarily failed for {name}; retrying in {RETRY_DELAYS[attempt]}s.', file=sys.stderr)
time.sleep(RETRY_DELAYS[attempt])
pending = [(name, body) for name, body in contents.items() if name not in names]
with ThreadPoolExecutor(max_workers=2) as executor:
# Consume every result so failures prevent the publication step.
list(executor.map(upload, pending))
+287
View File
@@ -0,0 +1,287 @@
"""Upload platform builds to a commit-bound draft, then verify and publish it."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import hashlib
import importlib.util
import io
import json
import os
from pathlib import Path
import urllib.error
import urllib.parse
import zipfile
from release_artifacts import AUDIT, FEED, INSTALLER, PORTABLE, app_versions, validate_metadata
import release_transport as transport
request = transport.request
fingerprint = transport.fingerprint
def context():
base = f"{transport.SERVER}/api/v1/repos/{os.environ['GITEA_REPOSITORY']}"
sha, tag = os.environ['GITEA_SHA'], os.environ['RELEASE_TAG']
version, windows_version = app_versions('pubspec.yaml')
if tag != f'v{version}':
raise ValueError('Release tag must match pubspec version')
remote_tag = request(f'{base}/tags/{urllib.parse.quote(tag, safe="")}')
if remote_tag['commit']['sha'] != sha:
raise ValueError('Release tag no longer matches the checked-out commit')
if os.environ.get('CI_RUN_ID'):
successful_ci(base, sha, int(os.environ['CI_RUN_ID']))
return base, sha, tag, version, windows_version
def marker(sha):
return f'<!-- cutdex-source-commit:{sha} -->'
def check_draft(release, sha, tag):
if not release.get('draft'):
raise ValueError('Release already published; choose a new version')
if release.get('tag_name') != tag or marker(sha) not in (release.get('body') or '').splitlines():
raise ValueError('Draft Release belongs to a different commit or release flow')
def ci_marker(run_id):
return f'<!-- cutdex-ci-run:{run_id} -->'
def successful_ci(base, sha, run_id=None):
runs = request(f'{base}/actions/runs?limit=100')['workflow_runs']
matches = [run for run in runs if run['head_sha'] == sha
and run['path'].endswith('@refs/heads/main')
and Path(run['path'].split('@')[0]).name == 'ci.yml'
and run['conclusion'] == 'success'
and (run_id is None or run['id'] == run_id)]
if not matches:
raise ValueError('No successful main CI for this exact commit; run CI before releasing')
return max(matches, key=lambda run: run['id'])
def ci_artifacts(base, run_id):
return [item for item in request(f'{base}/actions/runs/{run_id}/artifacts')['artifacts']
if not item.get('expired', False)]
def artifact_named(artifacts, name):
matches = [item for item in artifacts if item['name'] == name]
if len(matches) != 1:
raise ValueError('Expected one unexpired CI artifact: ' + name)
return matches[0]
def prepare_ci(base, sha, tag, version, windows_version):
# Keep retries bound to the original run, even if another same-commit CI
# succeeds later with different build bytes.
try:
existing = request(f'{base}/releases/tags/{urllib.parse.quote(tag, safe="")}')
except urllib.error.HTTPError as error:
if error.code != 404:
raise
existing = None
run_id = None
if existing is not None:
check_draft(existing, sha, tag)
import re
matches = re.findall(r'^<!-- cutdex-ci-run:(\d+) -->$', existing.get('body') or '', re.M)
if len(matches) != 1:
raise ValueError('Existing draft is not bound to a main CI run')
run_id = int(matches[0])
run = successful_ci(base, sha, run_id)
artifacts = ci_artifacts(base, run['id'])
verification = artifact_named(artifacts, 'cutdex-release-metadata')
selected = {platform: artifact_named(artifacts, f'cutdex-{platform}-build')
for platform in ('android', 'windows')}
release = prepare(base, sha, tag, version, windows_version, ci_run=run['id'])
if os.environ.get('GITHUB_OUTPUT'):
with open(os.environ['GITHUB_OUTPUT'], 'a', encoding='utf-8') as stream:
stream.write(f"sha={sha}\nci-run-id={run['id']}\nartifact-id={verification['id']}\n")
for platform, artifact in selected.items():
stream.write(f"{platform}-artifact-id={artifact['id']}\n")
return release
def prepare(base, sha, tag, version, windows_version, *, ci_run=None):
try:
release = request(f'{base}/releases/tags/{urllib.parse.quote(tag, safe="")}')
except urllib.error.HTTPError as error:
if error.code != 404:
raise
release = request(f'{base}/releases', {
'tag_name': tag, 'target_commitish': sha, 'name': f'Cutdex {version}',
'draft': True, 'prerelease': False,
'body': f'{marker(sha)}\n' + (f'{ci_marker(ci_run)}\n' if ci_run is not None else '')
+ 'Windows x64 installer, Portable ZIP and full update package; '
f'Android ARM64/x86_64 APK. Windows update version: {windows_version}. '
'Packages are reused from successful main CI and uploaded independently. '
'Publication waits for all checks. '
'Android currently uses the project debug signing key. '
'Processing workers and models are distributed separately.'}, 'POST')
check_draft(release, sha, tag)
if ci_run is not None and ci_marker(ci_run) not in (release.get('body') or '').splitlines():
raise ValueError('Draft Release belongs to a different CI run')
if os.environ.get('GITHUB_OUTPUT'):
with open(os.environ['GITHUB_OUTPUT'], 'a', encoding='utf-8') as stream:
stream.write(f"release-id={release['id']}\n")
return release
def upload_platform(base, release, contents):
"""Confirm upload presence; defer all byte verification to publication."""
transport.upload_contents(base, release['id'], contents, transport=request)
assets = request(f"{base}/releases/{release['id']}/assets")
names = [asset['name'] for asset in assets]
if len(set(names)) != len(names):
raise ValueError('Duplicate Release attachments')
if not set(contents) <= set(names):
raise ValueError('Missing uploaded platform attachments')
def asset_snapshot(assets):
return sorted((asset['id'], asset['name']) for asset in assets)
def verify_remote(base, release, metadata, manifest):
expected = dict(manifest['files'])
for name in ('SHA256SUMS', 'release-manifest.json'):
expected[name] = hashlib.sha256(metadata[name]).hexdigest()
assets = request(f"{base}/releases/{release['id']}/assets")
names = [asset['name'] for asset in assets]
if len(set(names)) != len(names) or set(names) != set(expected):
raise ValueError('Draft Release attachments differ from the validated artifact')
full = json.loads(metadata[FEED])['Assets'][0]
def verify(asset):
name = asset['name']
actual = fingerprint(asset)
if actual['sha256'] != expected[name]:
raise ValueError('Release attachment verification failed: ' + name)
if name == full['FileName'] and (actual['sha1'] != full['SHA1'].lower() or actual['size'] != full['Size']):
raise ValueError('Update index checksums do not match the full package')
with ThreadPoolExecutor(max_workers=2) as executor:
list(executor.map(verify, assets))
return asset_snapshot(assets)
def platform_contents(platform, path, version, windows_version):
if platform == 'android':
if path.is_dir():
expected = f'cutdex-{version}-android.apk'
if set(read_directory(path)) != {expected}:
raise ValueError('Expected exactly one Android APK')
path = path / expected
# Import lazily: assembling/uploading Windows must not require an APK.
spec = importlib.util.spec_from_file_location('package_app', Path(__file__).with_name('package-app.py'))
packaging = importlib.util.module_from_spec(spec)
spec.loader.exec_module(packaging)
packaging.validate_apk(path)
return {f'cutdex-{version}-android.apk': path.read_bytes()}
contents = read_directory(path)
# Validate the Windows feed/version/full-package hashes using the same
# complete-artifact validator before any bytes are uploaded.
required = {AUDIT, FEED, INSTALLER, PORTABLE}
if not required <= set(contents):
raise ValueError('Incomplete Windows packages')
dummy_apk = f'cutdex-{version}-android.apk'
if dummy_apk in contents or 'release-manifest.json' in contents or 'SHA256SUMS' in contents:
raise ValueError('Windows artifact contains unexpected release metadata')
validation = dict(contents)
validation[dummy_apk] = b''
spec = importlib.util.spec_from_file_location('package_app', Path(__file__).with_name('package-app.py'))
packaging = importlib.util.module_from_spec(spec)
spec.loader.exec_module(packaging)
packaging.assemble(validation, version, windows_version)
return contents
def read_directory(path):
paths = list(path.iterdir())
if any(not item.is_file() or item.is_symlink() for item in paths):
raise ValueError('Expected a flat package directory with regular files')
return {item.name: item.read_bytes() for item in paths}
def fetch_ci_artifact(base, command, path, version, windows_version):
run_id = int(os.environ['CI_RUN_ID'])
artifact_id = int(os.environ['CI_ARTIFACT_ID'])
artifacts = ci_artifacts(base, run_id)
matches = [item for item in artifacts if item['id'] == artifact_id]
if len(matches) != 1:
raise ValueError('Artifact does not belong to the selected CI run or has expired')
artifact = matches[0]
platform = command.removeprefix('fetch-')
expected = 'cutdex-release-metadata' if platform == 'release' else f'cutdex-{platform}-build'
if artifact['name'] != expected:
raise ValueError('Unexpected CI artifact type')
data = request(f'{base}/actions/artifacts/{artifact_id}/zip')
with zipfile.ZipFile(io.BytesIO(data)) as archive:
entries = [item for item in archive.infolist() if not item.is_dir()]
names = [item.filename for item in entries]
if len(set(names)) != len(names) or any('/' in name or '\\' in name for name in names):
raise ValueError('CI artifact requires unique flat filenames')
contents = {item.filename: archive.read(item) for item in entries}
apk_name = f'cutdex-{version}-android.apk'
if artifact['name'] == 'cutdex-release-metadata':
validate_metadata(contents, version, windows_version)
elif platform == 'android':
if set(contents) != {'app-production-release.apk'}:
raise ValueError('Unexpected Android build artifact')
contents = {apk_name: contents['app-production-release.apk']}
if path.exists() and any(path.iterdir()):
raise ValueError('CI artifact output directory must be empty')
path.mkdir(parents=True, exist_ok=True)
for name, body in contents.items():
(path / name).write_bytes(body)
if platform in {'android', 'windows'}:
platform_contents(platform, path, version, windows_version)
return artifact_id
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('command', choices=['prepare', 'prepare-ci', 'fetch-android', 'fetch-windows',
'fetch-release', 'android', 'windows', 'publish'])
parser.add_argument('--path', type=Path)
args = parser.parse_args()
if args.command not in {'prepare', 'prepare-ci'} and args.path is None:
parser.error('--path is required for uploading or publishing')
base, sha, tag, version, windows_version = context()
if args.command.startswith('fetch-'):
fetch_ci_artifact(base, args.command, args.path, version, windows_version)
return
if args.command == 'prepare-ci':
release = prepare_ci(base, sha, tag, version, windows_version)
elif args.command == 'prepare':
release = prepare(base, sha, tag, version, windows_version)
else:
release = request(f"{base}/releases/{int(os.environ['RELEASE_ID'])}")
check_draft(release, sha, tag)
if os.environ.get('CI_RUN_ID') and ci_marker(int(os.environ['CI_RUN_ID'])) not in (release.get('body') or '').splitlines():
raise ValueError('Draft Release belongs to a different CI run')
if args.command == 'publish':
contents = read_directory(args.path)
manifest = validate_metadata(contents, version, windows_version)
# Platform binaries must already have been independently uploaded.
metadata = {'SHA256SUMS', 'release-manifest.json'}
assets = request(f"{base}/releases/{release['id']}/assets")
if {asset['name'] for asset in assets} - metadata != set(manifest['files']):
raise ValueError('Not all platform packages have been uploaded')
transport.upload_contents(base, release['id'], {name: contents[name] for name in metadata}, transport=request)
snapshot = verify_remote(base, release, contents, manifest)
# Recheck tag binding and draft status immediately before publishing.
context()
check_draft(request(f"{base}/releases/{release['id']}"), sha, tag)
if snapshot != asset_snapshot(request(f"{base}/releases/{release['id']}/assets")):
raise ValueError('Release attachments changed during verification')
request(f"{base}/releases/{release['id']}", {'draft': False, 'prerelease': False}, 'PATCH')
else:
contents = platform_contents(args.command, args.path, version, windows_version)
upload_platform(base, release, contents)
print(json.dumps({'releaseId': release['id'], 'tag': tag, 'command': args.command}))
if __name__ == '__main__':
main()
+112
View File
@@ -0,0 +1,112 @@
import importlib.util
import io
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
import zipfile
from test_release_artifacts import fixture
from release_artifacts import METADATA, validate_artifact, validate_metadata
spec = importlib.util.spec_from_file_location('package_app', Path(__file__).with_name('package-app.py'))
packaging = importlib.util.module_from_spec(spec)
spec.loader.exec_module(packaging)
def apk_bytes(abis=('arm64-v8a', 'x86_64')):
stream = io.BytesIO()
with zipfile.ZipFile(stream, 'w') as archive:
for abi in abis:
archive.writestr(f'lib/{abi}/libflutter.so', b'flutter')
return stream.getvalue()
class SplitPackagingTests(unittest.TestCase):
def run_cli(self, root, *args):
with patch.object(packaging, 'ROOT', root), patch('sys.argv', ['package-app.py', *args]), patch('sys.stdout', io.StringIO()):
packaging.main()
def prepare(self, root):
(root / 'pubspec.yaml').write_text('version: 0.1.0+2\n')
apk = root / 'build/app/outputs/flutter-apk/app-production-release.apk'
apk.parent.mkdir(parents=True)
apk.write_bytes(apk_bytes())
packages = root / 'windows-packages'
packages.mkdir()
for name, body in fixture().items():
if name not in {'cutdex-0.1.0-android.apk', 'SHA256SUMS', 'release-manifest.json'}:
(packages / name).write_bytes(body)
return packages
def test_assemble_requires_no_windows_build_or_resolved_dependencies(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
packages = self.prepare(root)
self.run_cli(root, '--platform', 'assemble', '--windows-packages', str(packages))
contents = {p.name: p.read_bytes() for p in (root / 'dist').iterdir()}
validate_artifact(contents, '0.1.0', '0.1.0-build.2')
metadata = {p.name: p.read_bytes() for p in (root / '.build/release-metadata').iterdir()}
self.assertEqual(set(metadata), METADATA)
validate_metadata(metadata, '0.1.0', '0.1.0-build.2')
self.assertTrue(all(metadata[name] == contents[name] for name in metadata))
self.assertEqual(contents['cutdex-0.1.0-android.apk'],
(root / 'build/app/outputs/flutter-apk/app-production-release.apk').read_bytes())
def test_assemble_rejects_tampered_update_package_before_writing(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
packages = self.prepare(root)
next(packages.glob('*.nupkg')).write_bytes(b'tampered')
with self.assertRaisesRegex(ValueError, 'index checksums'):
self.run_cli(root, '--platform', 'assemble', '--windows-packages', str(packages))
self.assertFalse((root / 'dist').exists())
def test_assemble_rejects_missing_stale_or_nested_windows_packages(self):
for change in ('missing', 'stale', 'nested'):
with self.subTest(change=change), tempfile.TemporaryDirectory() as directory:
root = Path(directory)
packages = self.prepare(root)
if change == 'missing':
(packages / packaging.INSTALLER).unlink()
elif change == 'stale':
(packages / 'old.zip').write_bytes(b'old')
else:
(packages / 'nested').mkdir()
with self.assertRaises(ValueError):
self.run_cli(root, '--platform', 'assemble', '--windows-packages', str(packages))
self.assertFalse((root / 'dist').exists())
def test_windows_packaging_does_not_require_android(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / 'pubspec.yaml').write_text('version: 0.1.0+2\n')
windows = root / 'build/windows/x64/production/runner/Release'
windows.mkdir(parents=True)
(windows / 'cutdex.exe').write_bytes(b'exe')
with patch.object(packaging, 'package_windows', return_value={'windows.zip': b'zip'}) as pack:
self.run_cli(root, '--platform', 'windows', '--vpk', 'vpk.exe')
pack.assert_called_once_with(windows, Path('vpk.exe'), '0.1.0-build.2')
self.assertEqual({p.name for p in (root / 'dist').iterdir()}, {'windows.zip'})
def test_apk_rejects_missing_abi_and_32_bit_libraries(self):
for abis in [('arm64-v8a',), ('arm64-v8a', 'x86_64', 'armeabi-v7a')]:
with tempfile.TemporaryDirectory() as directory:
apk = Path(directory) / 'app.apk'
apk.write_bytes(apk_bytes(abis))
with self.assertRaises(ValueError):
packaging.validate_apk(apk)
def test_assemble_refuses_existing_output(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
packages = self.prepare(root)
(root / 'dist').mkdir()
(root / 'dist/stale.zip').write_bytes(b'stale')
with self.assertRaisesRegex(ValueError, 'dist must be empty'):
self.run_cli(root, '--platform', 'assemble', '--windows-packages', str(packages))
if __name__ == '__main__':
unittest.main()
+130
View File
@@ -0,0 +1,130 @@
import copy
import hashlib
import json
from pathlib import Path
import tempfile
import unittest
from release_artifacts import AUDIT, FEED, INSTALLER, PORTABLE, METADATA, app_versions, checksum_lines, validate_artifact, validate_metadata
def fixture():
package = 'Cutdex-0.1.0-build.2-win-x64-full.nupkg'
payload = b'full package'
feed = {'Assets': [{'PackageId': 'Cutdex', 'Version': '0.1.0-build.2', 'Type': 'Full',
'FileName': package, 'Size': len(payload),
'SHA1': hashlib.sha1(payload).hexdigest(),
'SHA256': hashlib.sha256(payload).hexdigest()}]}
contents = {'cutdex-0.1.0-android.apk': b'apk', INSTALLER: b'exe', PORTABLE: b'zip',
FEED: json.dumps(feed).encode(), AUDIT: b'{}', package: payload}
manifest = {'version': '0.1.0', 'windowsUpdateVersion': '0.1.0-build.2',
'windowsPackageId': 'Cutdex', 'windowsChannel': 'win-x64', 'files': {}}
return reseal(contents, manifest)
def reseal(contents, manifest=None):
if manifest is None:
manifest = json.loads(contents['release-manifest.json'])
manifest['files'] = {name: hashlib.sha256(body).hexdigest() for name, body in contents.items()
if name not in ['SHA256SUMS', 'release-manifest.json']}
contents['SHA256SUMS'] = checksum_lines(manifest['files']).encode()
contents['release-manifest.json'] = json.dumps(manifest).encode()
return contents
class ReleaseArtifactTests(unittest.TestCase):
def validate(self, contents):
return validate_artifact(contents, '0.1.0', '0.1.0-build.2')
def test_complete_installer_portable_and_update_release(self):
self.assertEqual(self.validate(fixture())['windowsPackageId'], 'Cutdex')
def test_missing_or_unexpected_attachments(self):
original = fixture()
for name in [INSTALLER, PORTABLE, 'Cutdex-0.1.0-build.2-win-x64-full.nupkg']:
contents = copy.deepcopy(original)
del contents[name]
with self.assertRaises(ValueError):
self.validate(contents)
contents = fixture()
contents['stale.zip'] = b'old'
with self.assertRaises(ValueError):
self.validate(reseal(contents))
def test_tampered_package_or_checksum_file(self):
for name in [INSTALLER, PORTABLE, 'SHA256SUMS']:
contents = fixture()
contents[name] += b'tampered'
with self.assertRaises(ValueError):
self.validate(contents)
def test_wrong_identity_version_delta_or_escaping_filename(self):
for key, value in [('PackageId', 'Cutdex.Dev'), ('Version', '0.1.0-build.1'),
('Type', 'Delta'), ('FileName', '../outside.nupkg')]:
contents = fixture()
feed = json.loads(contents[FEED])
feed['Assets'][0][key] = value
contents[FEED] = json.dumps(feed).encode()
with self.assertRaises(ValueError):
self.validate(reseal(contents))
def test_resealed_manifest_cannot_hide_index_checksum_mismatch(self):
for field in ['SHA1', 'SHA256', 'Size']:
contents = fixture()
feed = json.loads(contents[FEED])
feed['Assets'][0][field] = 0 if field == 'Size' else '0' * 64
contents[FEED] = json.dumps(feed).encode()
with self.assertRaisesRegex(ValueError, 'index checksums'):
self.validate(reseal(contents))
def test_stale_or_mixed_index_and_metadata_are_rejected(self):
contents = fixture()
feed = json.loads(contents[FEED])
feed['Assets'].append(dict(feed['Assets'][0]))
contents[FEED] = json.dumps(feed).encode()
with self.assertRaises(ValueError):
self.validate(reseal(contents))
for key, value in [('version', '0.0.9'), ('windowsChannel', 'dev-win-x64'),
('windowsUpdateVersion', '0.1.0-build.1')]:
contents = fixture()
manifest = json.loads(contents['release-manifest.json'])
manifest[key] = value
with self.assertRaises(ValueError):
self.validate(reseal(contents, manifest))
def test_build_number_is_part_of_update_version(self):
with tempfile.TemporaryDirectory() as directory:
spec = Path(directory) / 'pubspec.yaml'
spec.write_text('name: cutdex\nversion: 0.1.0+2\n')
self.assertEqual(app_versions(spec), ('0.1.0', '0.1.0-build.2'))
spec.write_text('version: 0.1.0\n')
with self.assertRaises(ValueError):
app_versions(spec)
def test_compact_metadata_validates_without_binary_packages(self):
contents = fixture()
metadata = {name: contents[name] for name in METADATA}
manifest = validate_metadata(metadata, '0.1.0', '0.1.0-build.2')
self.assertIn(INSTALLER, manifest['files'])
self.assertNotIn(INSTALLER, metadata)
def test_compact_metadata_rejects_missing_extra_or_tampered_files(self):
original = {name: body for name, body in fixture().items() if name in METADATA}
for name in METADATA:
with self.subTest(name=name):
metadata = dict(original)
del metadata[name]
with self.assertRaises(ValueError):
validate_metadata(metadata, '0.1.0', '0.1.0-build.2')
for name in ['SHA256SUMS', AUDIT, FEED]:
metadata = dict(original)
metadata[name] += b'corrupt'
with self.assertRaises(ValueError):
validate_metadata(metadata, '0.1.0', '0.1.0-build.2')
metadata = dict(original, unexpected=b'file')
with self.assertRaises(ValueError):
validate_metadata(metadata, '0.1.0', '0.1.0-build.2')
if __name__ == '__main__':
unittest.main()
+468
View File
@@ -0,0 +1,468 @@
import importlib.util
import hashlib
import io
from pathlib import Path
import tempfile
import threading
import unittest
from unittest.mock import patch
import urllib.error
import urllib.parse
import zipfile
from test_package_app import apk_bytes
from test_release_artifacts import fixture, reseal
from release_artifacts import METADATA
spec = importlib.util.spec_from_file_location('stage_release', Path(__file__).with_name('stage-release.py'))
stage = importlib.util.module_from_spec(spec)
spec.loader.exec_module(stage)
class StagedReleaseTests(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
self.root = Path(self.directory.name)
self.sha = 'a' * 40
self.remote_sha = self.sha
self.release = None
self.stored = {}
self.ids = {}
self.calls = []
self.corrupt_remote = False
self.fingerprint_calls = []
self.contents = fixture()
self.contents['cutdex-0.1.0-android.apk'] = apk_bytes()
reseal(self.contents)
self.ci_runs = [{'id': 1, 'head_sha': self.sha, 'conclusion': 'success',
'path': '.gitea/workflows/ci.yml@refs/heads/main'}]
self.run_artifacts = {1: [{'id': 10, 'name': 'cutdex-release-packages'},
{'id': 11, 'name': 'cutdex-android-build'},
{'id': 12, 'name': 'cutdex-windows-build'},
{'id': 13, 'name': 'cutdex-release-metadata'}]}
self.artifact_contents = {10: self.contents,
11: {'app-production-release.apk': self.contents['cutdex-0.1.0-android.apk']},
12: {name: body for name, body in self.contents.items()
if name not in {'cutdex-0.1.0-android.apk', 'SHA256SUMS', 'release-manifest.json'}}}
self.artifact_contents[13] = {name: self.contents[name] for name in METADATA}
self.apk = self.root / 'app.apk'
self.apk.write_bytes(self.contents['cutdex-0.1.0-android.apk'])
self.windows = self.root / 'windows'
self.windows.mkdir()
self.dist = self.root / 'dist'
self.dist.mkdir()
for name, body in self.contents.items():
if name in METADATA:
(self.dist / name).write_bytes(body)
if name not in {'cutdex-0.1.0-android.apk', 'SHA256SUMS', 'release-manifest.json'}:
(self.windows / name).write_bytes(body)
self.environment = {'GITEA_REPOSITORY': 'owner/cutdex', 'GITEA_SHA': self.sha,
'RELEASE_TAG': 'v0.1.0', 'RELEASE_ID': '3',
'GITHUB_OUTPUT': str(self.root / 'outputs')}
for patcher in [patch.dict('os.environ', self.environment),
patch.object(stage, 'request', side_effect=self.request),
patch.object(stage, 'fingerprint', side_effect=self.fingerprint),
patch.object(stage, 'app_versions', return_value=('0.1.0', '0.1.0-build.2'))]:
patcher.start()
self.addCleanup(patcher.stop)
def assets(self):
return [{'name': name, 'id': self.ids[name]} for name in self.stored]
def request(self, url, data=None, method=None, content_type=None):
self.calls.append((method, url))
if url.endswith('/actions/runs?limit=100'):
return {'workflow_runs': self.ci_runs}
if '/actions/runs/' in url and url.endswith('/artifacts'):
return {'artifacts': self.run_artifacts[int(url.split('/actions/runs/')[1].split('/')[0])]}
if '/actions/artifacts/' in url and url.endswith('/zip'):
contents = self.artifact_contents[int(url.split('/actions/artifacts/')[1].split('/')[0])]
stream = io.BytesIO()
with zipfile.ZipFile(stream, 'w') as archive:
for name, body in contents.items():
archive.writestr(name, body)
return stream.getvalue()
if url.endswith('/tags/v0.1.0') and '/releases/' not in url:
return {'commit': {'sha': self.remote_sha}}
if url.endswith('/releases/tags/v0.1.0'):
if self.release is None:
raise urllib.error.HTTPError(url, 404, 'missing', {}, None)
return dict(self.release)
if url.endswith('/releases') and method == 'POST':
self.release = dict(data, id=3)
return dict(self.release)
if url.endswith('/releases/3'):
if method == 'PATCH':
self.assertEqual(data, {'draft': False, 'prerelease': False})
self.release.update(data)
return dict(self.release)
if url.endswith('/releases/3/assets'):
return self.assets()
if '/assets?name=' in url and method == 'POST':
name = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)['name'][0]
boundary = content_type.split('boundary=')[1].encode()
self.stored[name] = data.split(b'\r\n\r\n', 1)[1].rsplit(b'\r\n--' + boundary, 1)[0]
self.ids[name] = max(self.ids.values(), default=0) + 1
return {'name': name, 'id': self.ids[name]}
if '/assets/' in url and method == 'DELETE':
asset_id = int(url.rsplit('/', 1)[1])
name = next(name for name in self.stored if self.ids[name] == asset_id)
del self.stored[name]
return b''
raise AssertionError('Unexpected request: ' + url)
def download(self, asset):
return self.stored[asset['name']] + (b'corrupt' if self.corrupt_remote else b'')
def fingerprint(self, asset):
self.fingerprint_calls.append(asset['name'])
body = self.download(asset)
return {'sha256': hashlib.sha256(body).hexdigest(), 'sha1': hashlib.sha1(body).hexdigest(), 'size': len(body)}
def run_cli(self, command, path=None):
args = ['stage-release.py', command]
if path is not None:
args += ['--path', str(path)]
with patch('sys.argv', args), patch('sys.stdout', io.StringIO()):
stage.main()
def upload_platforms(self):
self.run_cli('prepare')
self.run_cli('android', self.apk)
self.run_cli('windows', self.windows)
def assert_draft(self):
self.assertTrue(self.release['draft'])
self.assertFalse(any(method == 'PATCH' for method, _ in self.calls))
def test_android_upload_does_not_wait_for_windows_or_publish(self):
self.run_cli('prepare')
self.run_cli('android', self.apk)
self.assertEqual(set(self.stored), {'cutdex-0.1.0-android.apk'})
self.assert_draft()
self.assertEqual((self.root / 'outputs').read_text(), 'release-id=3\n')
def test_windows_can_finish_first_and_only_complete_release_is_published(self):
self.run_cli('prepare')
self.run_cli('windows', self.windows)
self.assertNotIn('cutdex-0.1.0-android.apk', self.stored)
self.assert_draft()
self.run_cli('android', self.apk)
before = len(self.calls)
self.run_cli('publish', self.dist)
uploads = [url for method, url in self.calls[before:] if method == 'POST']
self.assertEqual(len(uploads), 2) # Only final checksums and manifest.
self.assertEqual(self.stored, self.contents)
self.assertFalse(self.release['draft'])
def test_missing_platform_cannot_publish(self):
self.run_cli('prepare')
self.run_cli('android', self.apk)
with self.assertRaisesRegex(ValueError, 'Not all platform'):
self.run_cli('publish', self.dist)
self.assert_draft()
def test_remote_corruption_or_extra_asset_keeps_release_draft(self):
self.upload_platforms()
self.corrupt_remote = True
with self.assertRaisesRegex(ValueError, 'verification failed'):
self.run_cli('publish', self.dist)
self.assert_draft()
self.corrupt_remote = False
self.stored['stale.zip'] = b'stale'
self.ids['stale.zip'] = 999
with self.assertRaises(ValueError):
self.run_cli('publish', self.dist)
self.assert_draft()
def test_invalid_local_windows_package_never_uploads(self):
self.run_cli('prepare')
next(self.windows.glob('*.nupkg')).write_bytes(b'corrupt')
with self.assertRaisesRegex(ValueError, 'index checksums'):
self.run_cli('windows', self.windows)
self.assertEqual(self.stored, {})
self.assert_draft()
def test_tag_movement_and_different_commit_draft_are_rejected(self):
self.run_cli('prepare')
self.remote_sha = 'b' * 40
with self.assertRaisesRegex(ValueError, 'no longer matches'):
self.run_cli('android', self.apk)
self.remote_sha = self.sha
self.release['body'] = stage.marker('b' * 40)
with self.assertRaisesRegex(ValueError, 'different commit'):
self.run_cli('prepare')
self.assertEqual(self.stored, {})
def test_published_release_cannot_be_modified(self):
self.upload_platforms()
self.run_cli('publish', self.dist)
before = len(self.calls)
for command, path in [('prepare', None), ('android', self.apk), ('publish', self.dist)]:
with self.assertRaisesRegex(ValueError, 'already published'):
self.run_cli(command, path)
self.assertFalse(any(method in {'POST', 'PATCH', 'DELETE'} for method, _ in self.calls[before:]))
def test_retry_reuses_files_without_replacing_existing_attachments(self):
self.upload_platforms()
before = len(self.calls)
self.run_cli('prepare')
self.run_cli('android', self.apk)
self.assertFalse(any(method in {'POST', 'DELETE'} for method, _ in self.calls[before:]))
self.apk.write_bytes(self.apk.read_bytes() + b'new-build')
self.run_cli('android', self.apk)
self.assertEqual(self.stored['cutdex-0.1.0-android.apk'], self.contents['cutdex-0.1.0-android.apk'])
for name, body in self.contents.items():
if name not in {'cutdex-0.1.0-android.apk', 'SHA256SUMS', 'release-manifest.json'}:
self.assertEqual(self.stored[name], body)
self.assert_draft()
def test_authentication_failure_does_not_create_a_draft(self):
with patch.object(stage, 'request', side_effect=urllib.error.HTTPError('url', 403, 'forbidden', {}, None)):
with self.assertRaises(urllib.error.HTTPError):
stage.prepare('base', self.sha, 'v0.1.0', '0.1.0', '0.1.0-build.2')
self.assertIsNone(self.release)
def test_tag_moved_during_final_verification_is_not_published(self):
self.upload_platforms()
tag_checks = 0
def move_tag(url, *args, **kwargs):
nonlocal tag_checks
if url.endswith('/tags/v0.1.0') and '/releases/' not in url:
tag_checks += 1
if tag_checks == 2:
self.remote_sha = 'b' * 40
return self.request(url, *args, **kwargs)
with patch.object(stage, 'request', side_effect=move_tag):
with self.assertRaisesRegex(ValueError, 'no longer matches'):
self.run_cli('publish', self.dist)
self.assert_draft()
def test_invalid_final_manifest_never_uploads_metadata_or_publishes(self):
self.upload_platforms()
(self.dist / 'SHA256SUMS').write_bytes(b'corrupt')
before = len(self.calls)
with self.assertRaisesRegex(ValueError, 'SHA256SUMS'):
self.run_cli('publish', self.dist)
self.assertFalse(any(method in {'POST', 'DELETE', 'PATCH'} for method, _ in self.calls[before:]))
self.assert_draft()
def test_prepare_ci_selects_exact_successful_main_and_platform_artifacts(self):
self.ci_runs += [{'id': 2, 'head_sha': 'b' * 40, 'conclusion': 'success',
'path': '.gitea/workflows/ci.yml@refs/heads/main'},
{'id': 3, 'head_sha': self.sha, 'conclusion': 'success',
'path': '.gitea/workflows/ci.yml@refs/pull/4/head'}]
self.run_cli('prepare-ci')
output = (self.root / 'outputs').read_text()
for value in ['ci-run-id=1', 'artifact-id=13', 'android-artifact-id=11', 'windows-artifact-id=12']:
self.assertIn(value, output)
self.assertIn(stage.ci_marker(1), self.release['body'])
self.assert_draft()
def test_ci_failure_or_expired_metadata_never_creates_draft(self):
self.ci_runs[0]['conclusion'] = 'failure'
with self.assertRaisesRegex(ValueError, 'No successful main CI'):
self.run_cli('prepare-ci')
self.assertIsNone(self.release)
self.ci_runs[0]['conclusion'] = 'success'
self.run_artifacts[1][3]['expired'] = True
with self.assertRaisesRegex(ValueError, 'unexpired CI artifact'):
self.run_cli('prepare-ci')
self.assertIsNone(self.release)
def test_ci_retry_stays_on_original_run_after_new_same_commit_ci(self):
self.run_cli('prepare-ci')
self.ci_runs.append(dict(self.ci_runs[0], id=2))
self.run_artifacts[2] = [{'id': 20, 'name': 'cutdex-release-packages'}]
self.run_cli('prepare-ci')
self.assertNotIn('ci-run-id=2', (self.root / 'outputs').read_text())
with patch.dict('os.environ', {'CI_RUN_ID': '2'}):
with self.assertRaisesRegex(ValueError, 'different CI run'):
self.run_cli('android', self.apk)
self.assertEqual(self.stored, {})
def test_missing_or_expired_platform_artifacts_fail_before_creating_draft(self):
for platform in ('android', 'windows'):
artifact = next(item for item in self.run_artifacts[1] if item['name'] == f'cutdex-{platform}-build')
artifact['expired'] = True
with self.assertRaisesRegex(ValueError, f'cutdex-{platform}-build'):
self.run_cli('prepare-ci')
self.assertIsNone(self.release)
artifact['expired'] = False
self.run_artifacts[1].remove(artifact)
with self.assertRaisesRegex(ValueError, f'cutdex-{platform}-build'):
self.run_cli('prepare-ci')
self.assertIsNone(self.release)
self.run_artifacts[1].append(artifact)
def test_complete_archive_cannot_replace_new_artifact_types(self):
self.run_cli('prepare-ci')
with patch.dict('os.environ', {'CI_RUN_ID': '1', 'CI_ARTIFACT_ID': '10'}):
for command in ('fetch-android', 'fetch-windows', 'fetch-release'):
with self.assertRaisesRegex(ValueError, 'Unexpected CI artifact type'):
self.run_cli(command, self.root / 'legacy-archive')
self.assertFalse(any('/actions/artifacts/10/zip' in url for _, url in self.calls))
self.assertFalse((self.root / 'legacy-archive').exists())
def test_publish_rejects_complete_archive_input(self):
self.upload_platforms()
complete = self.root / 'complete'
complete.mkdir()
for name, body in self.contents.items():
(complete / name).write_bytes(body)
before = len(self.calls)
with self.assertRaisesRegex(ValueError, 'Release metadata requires'):
self.run_cli('publish', complete)
self.assertFalse(any(method in {'POST', 'DELETE', 'PATCH'} for method, _ in self.calls[before:]))
self.assert_draft()
def test_missing_metadata_cannot_fall_back_to_complete_archive(self):
self.run_artifacts[1] = [item for item in self.run_artifacts[1]
if item['name'] != 'cutdex-release-metadata']
with self.assertRaisesRegex(ValueError, 'cutdex-release-metadata'):
self.run_cli('prepare-ci')
self.assertIsNone(self.release)
def test_preferred_platform_artifacts_are_downloaded_and_validated(self):
self.run_cli('prepare-ci')
for platform, artifact_id in [('android', '11'), ('windows', '12')]:
destination = self.root / f'fetched-{platform}'
with patch.dict('os.environ', {'CI_RUN_ID': '1', 'CI_ARTIFACT_ID': artifact_id}):
self.run_cli(f'fetch-{platform}', destination)
self.run_cli(platform, destination)
self.assert_draft()
with patch.dict('os.environ', {'CI_RUN_ID': '1', 'CI_ARTIFACT_ID': '13'}):
self.run_cli('publish', self.dist)
self.assertFalse(self.release['draft'])
def test_artifact_from_wrong_run_expired_or_tampered_is_rejected(self):
self.run_cli('prepare-ci')
destination = self.root / 'rejected'
with patch.dict('os.environ', {'CI_RUN_ID': '1', 'CI_ARTIFACT_ID': '99'}):
with self.assertRaisesRegex(ValueError, 'does not belong'):
self.run_cli('fetch-release', destination)
self.run_artifacts[1][3]['expired'] = True
with patch.dict('os.environ', {'CI_RUN_ID': '1', 'CI_ARTIFACT_ID': '13'}):
with self.assertRaisesRegex(ValueError, 'has expired'):
self.run_cli('fetch-release', destination)
self.run_artifacts[1][3]['expired'] = False
self.artifact_contents[13][stage.AUDIT] = b'tampered'
with self.assertRaisesRegex(ValueError, 'checksum mismatch'):
self.run_cli('fetch-release', destination)
self.assertFalse(destination.exists())
self.assert_draft()
def test_unsafe_archive_paths_are_rejected_before_extraction(self):
self.run_cli('prepare-ci')
self.artifact_contents[11]['../outside.apk'] = b'bad'
destination = self.root / 'rejected'
with patch.dict('os.environ', {'CI_RUN_ID': '1', 'CI_ARTIFACT_ID': '11'}):
with self.assertRaisesRegex(ValueError, 'unique flat filenames'):
self.run_cli('fetch-android', destination)
self.assertFalse(destination.exists())
def test_platform_bytes_must_match_complete_ci_artifact_before_publication(self):
self.run_cli('prepare-ci')
self.artifact_contents[11]['app-production-release.apk'] += b'different-build'
with patch.dict('os.environ', {'CI_RUN_ID': '1'}):
for platform, artifact_id in [('android', '11'), ('windows', '12')]:
destination = self.root / f'fetched-{platform}'
with patch.dict('os.environ', {'CI_ARTIFACT_ID': artifact_id}):
self.run_cli(f'fetch-{platform}', destination)
self.run_cli(platform, destination)
with self.assertRaisesRegex(ValueError, 'verification failed'):
self.run_cli('publish', self.dist)
self.assert_draft()
def add_compact_metadata(self):
self.artifact_contents[13] = {name: self.contents[name] for name in METADATA}
def test_compact_metadata_avoids_complete_download_and_verifies_each_file_once(self):
self.add_compact_metadata()
self.run_cli('prepare-ci')
self.assertIn('artifact-id=13', (self.root / 'outputs').read_text())
with patch.dict('os.environ', {'CI_RUN_ID': '1'}):
for platform, artifact_id in [('windows', '12'), ('android', '11')]:
path = self.root / f'compact-{platform}'
with patch.dict('os.environ', {'CI_ARTIFACT_ID': artifact_id}):
self.run_cli(f'fetch-{platform}', path)
self.run_cli(platform, path)
self.assertEqual(self.fingerprint_calls, [])
path = self.root / 'compact-metadata'
with patch.dict('os.environ', {'CI_ARTIFACT_ID': '13'}):
self.run_cli('fetch-release', path)
self.assertEqual({p.name for p in path.iterdir()}, METADATA)
self.run_cli('publish', path)
self.assertFalse(self.release['draft'])
self.assertEqual(sorted(self.fingerprint_calls), sorted(self.contents))
self.assertFalse(any('/actions/artifacts/10/zip' in url for _, url in self.calls))
def test_invalid_compact_metadata_is_rejected_without_binary_download(self):
self.add_compact_metadata()
self.artifact_contents[13]['SHA256SUMS'] = b'bad'
self.run_cli('prepare-ci')
path = self.root / 'invalid-metadata'
with patch.dict('os.environ', {'CI_RUN_ID': '1', 'CI_ARTIFACT_ID': '13'}):
with self.assertRaisesRegex(ValueError, 'SHA256SUMS'):
self.run_cli('fetch-release', path)
self.assertFalse(path.exists())
self.assert_draft()
def test_remote_corruption_is_detected_with_metadata_only(self):
self.upload_platforms()
path = self.root / 'compact-metadata'
path.mkdir()
for name in METADATA:
(path / name).write_bytes(self.contents[name])
self.corrupt_remote = True
with self.assertRaisesRegex(ValueError, 'verification failed'):
self.run_cli('publish', path)
self.assert_draft()
def test_attachment_replacement_during_verification_blocks_publication(self):
self.upload_platforms()
count = 0
def changed_fingerprint(asset):
nonlocal count
result = self.fingerprint(asset)
count += 1
if count == len(self.contents):
self.ids[asset['name']] += 100
return result
with patch.object(stage, 'fingerprint', side_effect=changed_fingerprint):
with self.assertRaisesRegex(ValueError, 'changed during verification'):
self.run_cli('publish', self.dist)
self.assert_draft()
def test_remote_verification_runs_with_two_workers(self):
self.upload_platforms()
barrier = threading.Barrier(2)
lock = threading.Lock()
active, maximum = 0, 0
def parallel_fingerprint(asset):
nonlocal active, maximum
with lock:
active += 1
maximum = max(maximum, active)
try:
barrier.wait(timeout=5)
return self.fingerprint(asset)
finally:
with lock:
active -= 1
# There are eight attachments, so each pair reaches the barrier.
with patch.object(stage, 'fingerprint', side_effect=parallel_fingerprint):
self.run_cli('publish', self.dist)
self.assertEqual(maximum, 2)
self.assertFalse(self.release['draft'])
if __name__ == '__main__':
unittest.main()
+257
View File
@@ -0,0 +1,257 @@
import hashlib
import io
import threading
import unittest
import urllib.error
from unittest.mock import patch
import release_transport as transfers
class TransferToolsTests(unittest.TestCase):
def setUp(self):
environment = patch.dict('os.environ', {'CUTDEX_GITEA_INTERNAL_URL': ''})
environment.start()
self.addCleanup(environment.stop)
def test_local_api_transport_preserves_authenticated_request_and_public_identity(self):
class Response(io.BytesIO):
headers = {'Content-Type': 'application/json'}
with patch.dict('os.environ', {'CUTDEX_GITEA_INTERNAL_URL': 'http://127.0.0.1:3000/',
'GITEA_TOKEN': 'test-token'}), \
patch.object(transfers.urllib.request, 'urlopen', return_value=Response(b'{"id":3}')) as open_url:
result = transfers.request(transfers.SERVER + '/api/v1/releases?name=a%20b',
data=b'package', method='POST', content_type='application/octet-stream')
request = open_url.call_args.args[0]
self.assertEqual(result, {'id': 3})
self.assertEqual(request.full_url, 'http://127.0.0.1:3000/api/v1/releases?name=a%20b')
self.assertEqual(request.get_method(), 'POST')
self.assertEqual(request.get_header('Authorization'), 'token test-token')
self.assertEqual(request.get_header('Host'), 'git.orangraph.com')
self.assertEqual(request.data, b'package')
self.assertEqual(transfers.SERVER, 'https://git.orangraph.com')
def test_local_verification_routes_validated_attachment_without_changing_its_public_url(self):
asset = {'browser_download_url': 'https://git.orangraph.com/attachments/example'}
with patch.dict('os.environ', {'CUTDEX_GITEA_INTERNAL_URL': 'http://127.0.0.1:3000',
'GITEA_TOKEN': 'test-token'}), \
patch.object(transfers.urllib.request, 'urlopen', return_value=io.BytesIO(b'app')) as open_url:
result = transfers.fingerprint(asset)
self.assertEqual(open_url.call_args.args[0].full_url, 'http://127.0.0.1:3000/attachments/example')
self.assertEqual(open_url.call_args.args[0].get_header('Host'), 'git.orangraph.com')
self.assertEqual(result['sha256'], hashlib.sha256(b'app').hexdigest())
self.assertEqual(asset['browser_download_url'], 'https://git.orangraph.com/attachments/example')
def test_local_transport_rejects_unexpected_endpoint_or_origin_before_sending_credentials(self):
for internal, url, message in [
('http://example.com:3000', transfers.SERVER + '/api/v1/releases', 'internal Gitea endpoint'),
('http://127.0.0.1:3000', 'https://example.com/file', 'transport origin'),
('http://127.0.0.1:3000', 'http://git.orangraph.com/file', 'transport origin'),
]:
with self.subTest(internal=internal, url=url), \
patch.dict('os.environ', {'CUTDEX_GITEA_INTERNAL_URL': internal, 'GITEA_TOKEN': 'test-token'}), \
patch.object(transfers.urllib.request, 'urlopen') as open_url:
with self.assertRaisesRegex(ValueError, message):
transfers.request(url)
open_url.assert_not_called()
def test_frp_tunnel_not_found_page_is_retried_as_a_temporary_failure(self):
calls = 0
def transport(url, data=None, method=None, content_type=None):
nonlocal calls
if method is None:
return []
calls += 1
if calls == 1:
body = b'<h1>Not Found</h1><a href="https://github.com/fatedier/frp">frp</a>'
raise urllib.error.HTTPError(url, 404, 'Not Found',
{'Content-Type': 'text/html; charset=utf-8'}, io.BytesIO(body))
return {}
with patch.object(transfers.time, 'sleep') as sleep:
transfers.upload_contents('base', 3, {'app.zip': b'app'}, transport=transport)
self.assertEqual(calls, 2)
sleep.assert_called_once_with(5)
def test_ordinary_html_not_found_and_json_api_errors_are_not_retried(self):
for content_type, body in [('text/html', b'<h1>Not Found</h1>'),
('application/json', b'Not Found github.com/fatedier/frp')]:
with self.subTest(content_type=content_type):
error = urllib.error.HTTPError('url', 404, 'Not Found',
{'Content-Type': content_type}, io.BytesIO(body))
self.assertFalse(transfers.transient(error))
def test_transient_upload_failure_retries_without_restarting_other_files(self):
calls = []
def transport(url, data=None, method=None, content_type=None):
if method is None:
return []
calls.append(url)
if url.endswith('name=retry.zip') and calls.count(url) == 1:
raise urllib.error.URLError('connection reset')
return {}
with patch.object(transfers.time, 'sleep') as sleep:
transfers.upload_contents('base', 3, {'retry.zip': b'a', 'ok.zip': b'b'}, transport=transport)
self.assertEqual(sum(url.endswith('name=retry.zip') for url in calls), 2)
self.assertEqual(sum(url.endswith('name=ok.zip') for url in calls), 1)
sleep.assert_called_once_with(5)
def test_response_lost_after_upload_does_not_duplicate_attachment(self):
for committed_on in (1, 3):
with self.subTest(committed_on=committed_on):
calls = 0
assets = []
def transport(url, data=None, method=None, content_type=None):
nonlocal calls
if method is None:
return assets
calls += 1
if calls == committed_on:
assets.append({'name': 'app.zip'})
raise TimeoutError('response lost')
with patch.object(transfers.time, 'sleep'):
transfers.upload_contents('base', 3, {'app.zip': b'app'}, transport=transport)
self.assertEqual(calls, committed_on)
self.assertEqual(len(assets), 1)
def test_upload_retries_are_bounded_and_last_error_is_propagated(self):
calls = 0
def transport(url, data=None, method=None, content_type=None):
nonlocal calls
if method is None:
return []
calls += 1
raise urllib.error.HTTPError(url, 503, 'Unavailable', {}, None)
with patch.object(transfers.time, 'sleep') as sleep:
with self.assertRaises(urllib.error.HTTPError):
transfers.upload_contents('base', 3, {'app.zip': b'app'}, transport=transport)
self.assertEqual(calls, 3)
self.assertEqual([call.args[0] for call in sleep.call_args_list], [5, 15])
def test_permanent_upload_errors_fail_without_retries(self):
for status in (400, 401, 403, 404, 409, 422):
with self.subTest(status=status):
calls = 0
def transport(url, data=None, method=None, content_type=None):
nonlocal calls
if method is None:
return []
calls += 1
raise urllib.error.HTTPError(url, status, 'Permanent failure', {}, None)
with patch.object(transfers.time, 'sleep') as sleep:
with self.assertRaises(urllib.error.HTTPError):
transfers.upload_contents('base', 3, {'app.zip': b'app'}, transport=transport)
self.assertEqual(calls, 1)
sleep.assert_not_called()
def test_retry_reconciliation_rejects_duplicate_attachments(self):
reads, uploads = 0, 0
def transport(url, data=None, method=None, content_type=None):
nonlocal reads, uploads
if method is None:
reads += 1
return [] if reads == 1 else [{'name': 'app.zip'}, {'name': 'app.zip'}]
uploads += 1
raise TimeoutError('response lost')
with patch.object(transfers.time, 'sleep'):
with self.assertRaisesRegex(ValueError, 'Duplicate Release attachments'):
transfers.upload_contents('base', 3, {'app.zip': b'app'}, transport=transport)
self.assertEqual(uploads, 1)
def test_attachment_list_retries_rate_limiting_before_upload(self):
reads, uploads = 0, 0
def transport(url, data=None, method=None, content_type=None):
nonlocal reads, uploads
if method is None:
reads += 1
if reads == 1:
raise urllib.error.HTTPError(url, 429, 'Rate limited', {}, None)
return []
uploads += 1
return {}
with patch.object(transfers.time, 'sleep') as sleep:
transfers.upload_contents('base', 3, {'app.zip': b'app'}, transport=transport)
self.assertEqual((reads, uploads), (2, 1))
sleep.assert_called_once_with(5)
def test_uploads_run_with_at_most_two_workers(self):
barrier = threading.Barrier(2)
lock = threading.Lock()
active, maximum = 0, 0
uploads = []
def transport(url, data=None, method=None, content_type=None):
nonlocal active, maximum
if method is None:
return []
self.assertEqual(method, 'POST')
with lock:
active += 1
maximum = max(maximum, active)
try:
barrier.wait(timeout=5)
with lock:
uploads.append(url)
return {}
finally:
with lock:
active -= 1
transfers.upload_contents('base', 3, {f'file-{i}.zip': b'file' for i in range(4)}, transport=transport)
self.assertEqual(maximum, 2)
self.assertEqual(len(uploads), 4)
def test_worker_failure_is_propagated(self):
def transport(url, data=None, method=None, content_type=None):
if method is None:
return []
raise OSError('upload failed')
with self.assertRaisesRegex(OSError, 'upload failed'):
transfers.upload_contents('base', 3, {'first.zip': b'a', 'second.zip': b'b'}, transport=transport)
def test_invalid_filename_is_rejected_before_any_upload(self):
with patch.object(transfers, 'request', return_value=[]) as request:
with self.assertRaisesRegex(ValueError, 'Unexpected artifact path'):
transfers.upload_contents('base', 3, {'valid.zip': b'a', '../invalid.zip': b'b'})
self.assertEqual(request.call_count, 1)
def test_streaming_fingerprint_never_reads_entire_response_at_once(self):
body = b'a' * (1024 * 1024 + 123)
class Response(io.BytesIO):
def read(self, size=-1):
if size != 1024 * 1024:
raise AssertionError('Expected bounded chunk reads')
return super().read(size)
with patch.dict('os.environ', {'GITEA_TOKEN': 'test-token'}), \
patch.object(transfers.urllib.request, 'urlopen', return_value=Response(body)) as open_url:
result = transfers.fingerprint({'browser_download_url': 'http://git.orangraph.com/attachments/example'})
self.assertEqual(result, {'sha256': hashlib.sha256(body).hexdigest(),
'sha1': hashlib.sha1(body).hexdigest(), 'size': len(body)})
self.assertEqual(open_url.call_args.args[0].full_url, 'https://git.orangraph.com/attachments/example')
def test_streaming_verification_rejects_unexpected_host(self):
with patch.object(transfers.urllib.request, 'urlopen') as open_url:
with self.assertRaisesRegex(ValueError, 'Unexpected attachment host'):
transfers.fingerprint({'browser_download_url': 'https://example.com/file'})
open_url.assert_not_called()
if __name__ == '__main__':
unittest.main()
+31 -3
View File
@@ -5,11 +5,15 @@ import 'dart:io';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:deskup/deskup.dart';
const channel = MethodChannel('deskup'); const channel = MethodChannel('deskup');
const smokeRoot = String.fromEnvironment('CUTDEX_UPDATE_SMOKE_ROOT'); const smokeRoot = String.fromEnvironment('CUTDEX_UPDATE_SMOKE_ROOT');
void main() { List<String> restartArguments = [];
void main(List<String> arguments) {
restartArguments = arguments;
WidgetsFlutterBinding.ensureInitialized(); WidgetsFlutterBinding.ensureInitialized();
// The isolated smoke fixture depends only on Flutter, without Riverpod. // The isolated smoke fixture depends only on Flutter, without Riverpod.
// ignore: riverpod_lint/missing_provider_scope // ignore: riverpod_lint/missing_provider_scope
@@ -48,13 +52,33 @@ Future<void> runSmoke() async {
throw StateError('Set CUTDEX_UPDATE_SMOKE_ROOT for this test app'); throw StateError('Set CUTDEX_UPDATE_SMOKE_ROOT for this test app');
} }
try { try {
await channel.invokeMethod<void>('ready'); final updater = Deskup(
windows: WindowsUpdateConfiguration(
source: WebUpdateSource(
url: Uri.parse(
const String.fromEnvironment('CUTDEX_WINDOWS_UPDATE_URL'),
),
allowLocalHttp: true,
),
expectedPackageId: 'Cutdex.Dev',
preferenceNamespace: 'Cutdex.UpdateSmoke',
automaticCheckInterval: const Duration(minutes: 5),
maximumDeltas: -1,
),
);
await updater.initialize();
final initial = await waitFor( final initial = await waitFor(
(value) => value['configured'] == true && value['canCheck'] == true, (value) => value['configured'] == true && value['canCheck'] == true,
); );
await channel.invokeMethod<void>('check'); await channel.invokeMethod<void>('check');
var checked = await waitFor((value) => value['canCheck'] == true); var checked = await waitFor((value) => value['canCheck'] == true);
if (initial['build'] == '900002') { if (initial['build'] == '900002') {
if (!restartArguments.contains('--deskup-smoke-restart') ||
!restartArguments.contains('文档 with spaces')) {
throw StateError(
'Restart arguments were not preserved: $restartArguments',
);
}
if (checked['phase'] != 'current') { if (checked['phase'] != 'current') {
throw StateError('Updated version was offered again: $checked'); throw StateError('Updated version was offered again: $checked');
} }
@@ -78,7 +102,11 @@ Future<void> runSmoke() async {
} }
await record('before', checked); await record('before', checked);
await channel.invokeMethod<void>('validateInstall'); await channel.invokeMethod<void>('validateInstall');
await channel.invokeMethod<void>('install'); await updater.install(
silent: true,
restart: true,
restartArguments: ['--deskup-smoke-restart', '文档 with spaces'],
);
} catch (error, stack) { } catch (error, stack) {
await record('failure', {'error': '$error', 'stack': '$stack'}); await record('failure', {'error': '$error', 'stack': '$stack'});
exit(1); exit(1);
+1
View File
@@ -18,6 +18,7 @@ class CliTests(unittest.TestCase):
'macos/test_check_macos_release.py', 'windows/check_windows_release.py', 'macos/test_check_macos_release.py', 'windows/check_windows_release.py',
'windows/package_windows_release.py', 'windows/prepare_windows_sandbox.py', 'windows/package_windows_release.py', 'windows/prepare_windows_sandbox.py',
'windows/windows_updates.py', 'windows/test_windows_updates.py', 'windows/windows_updates.py', 'windows/test_windows_updates.py',
'gitea/package-app.py',
'diagnostics/frame_budget.py', 'diagnostics/frame_budget.py',
] ]
for name in scripts: for name in scripts:
+13 -7
View File
@@ -15,7 +15,7 @@ import sys
import threading import threading
import time import time
from windows_updates import DESKUP_VERSION, ROOT, check_tool, pack_release, update_version, vpk_command from windows_updates import ROOT, check_tool, pack_release, resolved_deskup, update_version, verify_sdk_version, vpk_command
class TestHandler(SimpleHTTPRequestHandler): class TestHandler(SimpleHTTPRequestHandler):
@@ -49,12 +49,14 @@ def main():
if work.exists(): if work.exists():
parser.error('Use a new work directory so previous reports cannot pass this test') parser.error('Use a new work directory so previous reports cannot pass this test')
work.mkdir(parents=True) work.mkdir(parents=True)
deskup_root = resolved_deskup()
verify_sdk_version()
command = vpk_command(args.vpk) command = vpk_command(args.vpk)
check_tool(command) check_tool(command)
definitions = work / 'defines.json' definitions = work / 'defines.json'
definitions.write_text(json.dumps({'CUTDEX_UPDATE_SMOKE_ROOT': work.as_posix()}), encoding='utf-8') definitions.write_text(json.dumps({'CUTDEX_UPDATE_SMOKE_ROOT': work.as_posix(),
environment = dict(os.environ, CUTDEX_WINDOWS_UPDATE_URL=f'http://127.0.0.1:{args.port}', 'CUTDEX_WINDOWS_UPDATE_URL': f'http://127.0.0.1:{args.port}'}), encoding='utf-8')
CUTDEX_UPDATE_TEST_HTTP='1') environment = dict(os.environ)
# Isolate Flutter caches, generated runner files and output from live builds. # Isolate Flutter caches, generated runner files and output from live builds.
source = work / 'source' source = work / 'source'
source.mkdir() source.mkdir()
@@ -65,9 +67,9 @@ def main():
# Media processing is covered separately and need not be rebuilt here. # Media processing is covered separately and need not be rebuilt here.
(source / 'pubspec.yaml').write_text( (source / 'pubspec.yaml').write_text(
'name: cutdex_update_smoke\nversion: 1.0.0+1\n' 'name: cutdex_update_smoke\nversion: 1.0.0+1\n'
'environment:\n sdk: ^3.13.2\n' 'environment:\n sdk: ^3.13.4\n'
'dependencies:\n flutter:\n sdk: flutter\n' 'dependencies:\n flutter:\n sdk: flutter\n'
f' deskup: {DESKUP_VERSION}\n' f' deskup:\n path: {deskup_root.as_posix()}\n'
'flutter:\n uses-material-design: true\n', encoding='utf-8') 'flutter:\n uses-material-design: true\n', encoding='utf-8')
entry = source / 'tool/testing/windows_update_smoke.dart' entry = source / 'tool/testing/windows_update_smoke.dart'
entry.parent.mkdir(parents=True) entry.parent.mkdir(parents=True)
@@ -103,7 +105,11 @@ def verify_update(work, port):
app = work / 'installed/Cutdex update test.exe' app = work / 'installed/Cutdex update test.exe'
process = None process = None
try: try:
process = subprocess.Popen([str(app)], cwd=app.parent, creationflags=subprocess.CREATE_NO_WINDOW) # The loopback fixture must not depend on a developer's HTTP proxy.
environment = {name: value for name, value in os.environ.items()
if name.lower() not in ('http_proxy', 'https_proxy', 'all_proxy')}
process = subprocess.Popen([str(app)], cwd=app.parent, env=environment,
creationflags=subprocess.CREATE_NO_WINDOW)
deadline = time.monotonic() + 240 deadline = time.monotonic() + 240
while time.monotonic() < deadline: while time.monotonic() < deadline:
if (work / 'failure.json').exists(): if (work / 'failure.json').exists():
+29 -1
View File
@@ -1,14 +1,42 @@
import hashlib import hashlib
import importlib.util
import json import json
from pathlib import Path from pathlib import Path
from unittest.mock import patch from unittest.mock import patch
import tempfile import tempfile
import unittest import unittest
from windows_updates import resolved_deskup, numeric_version, pack_release, update_version, validate_previous, verify_manifest from windows_updates import SDK_VERSION, check_tool, resolved_deskup, numeric_version, pack_release, update_version, validate_previous, verify_manifest, verify_sdk_version
class UpdatePublicationTests(unittest.TestCase): class UpdatePublicationTests(unittest.TestCase):
def test_packaging_module_imports_in_clean_checkout_without_flutter_config(self):
spec = importlib.util.spec_from_file_location('isolated_windows_updates',
Path(__file__).with_name('windows_updates.py'))
module = importlib.util.module_from_spec(spec)
with patch.object(Path, 'is_file', return_value=False):
spec.loader.exec_module(module)
self.assertEqual(module.SDK_VERSION, SDK_VERSION)
def test_packaging_tool_check_does_not_resolve_flutter_dependencies(self):
from subprocess import CompletedProcess
with patch('windows_updates.resolved_deskup', side_effect=AssertionError('No Flutter config')), \
patch('windows_updates.subprocess.run', return_value=CompletedProcess([], 0, f'vpk {SDK_VERSION}', '')):
check_tool(['vpk'])
def test_build_sdk_check_rejects_mismatched_and_missing_versions(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
cmake = root / 'windows/velopack.cmake'
cmake.parent.mkdir()
with patch('windows_updates.resolved_deskup', return_value=root):
for contents in ('set(DESKUP_VELOPACK_VERSION "9.9.9")', ''):
cmake.write_text(contents)
with self.assertRaisesRegex(ValueError, 'Resolved deskup must use'):
verify_sdk_version()
cmake.write_text(f'set(DESKUP_VELOPACK_VERSION "{SDK_VERSION}")')
self.assertEqual(verify_sdk_version(), SDK_VERSION)
def test_deskup_is_located_from_resolved_package_config(self): def test_deskup_is_located_from_resolved_package_config(self):
with tempfile.TemporaryDirectory(prefix='deskup package ') as directory: with tempfile.TemporaryDirectory(prefix='deskup package ') as directory:
root = Path(directory) root = Path(directory)
+18
View File
@@ -0,0 +1,18 @@
"""Windows update version ordering, independent of Flutter package resolution."""
import re
def update_version(display_version, build):
version = display_version + '-build.' + str(int(build))
numeric_version(version)
return version
def numeric_version(version):
number = r'(0|[1-9]\d*)'
match = re.fullmatch(rf'{number}\.{number}\.{number}(?:-build\.{number})?', version)
if not match:
raise ValueError('Windows update versions must use major.minor.patch-build.number')
major, minor, patch, build = match.groups()
# SemVer +build metadata does not participate in precedence.
return (int(major), int(minor), int(patch), int(build is None), int(build or 0))
+31 -34
View File
@@ -12,8 +12,12 @@ from urllib.parse import urljoin, urlparse
from urllib.request import url2pathname from urllib.request import url2pathname
from check_windows_release import audit from check_windows_release import audit
from update_versions import numeric_version, update_version
ROOT = Path(__file__).resolve().parents[2] ROOT = Path(__file__).resolve().parents[2]
SDK_VERSION = '1.2.161'
def resolved_deskup(): def resolved_deskup():
config = ROOT / '.dart_tool/package_config.json' config = ROOT / '.dart_tool/package_config.json'
if not config.is_file(): if not config.is_file():
@@ -26,12 +30,13 @@ def resolved_deskup():
return Path(url2pathname(uri.path)) return Path(url2pathname(uri.path))
DESKUP_ROOT = resolved_deskup() def verify_sdk_version():
DESKUP_VERSION = re.search(r'^version: ([^\s]+)', """Validate the resolved build SDK before saving the app for later packaging."""
(DESKUP_ROOT / 'pubspec.yaml').read_text(encoding='utf-8'), cmake = (resolved_deskup() / 'windows/velopack.cmake').read_text(encoding='utf-8')
re.MULTILINE).group(1) match = re.search(r'set\(DESKUP_VELOPACK_VERSION "([^"]+)"\)', cmake)
SDK_VERSION = re.search(r'set\(DESKUP_VELOPACK_VERSION "([^"]+)"\)', if not match or match[1] != SDK_VERSION:
(DESKUP_ROOT / 'windows/velopack.cmake').read_text(encoding='utf-8')).group(1) raise ValueError(f'Resolved deskup must use Velopack SDK {SDK_VERSION}')
return SDK_VERSION
def vpk_command(path): def vpk_command(path):
@@ -58,12 +63,6 @@ def pack_release(command, *, app, output, package_id, version, title):
'--delta', 'none'], check=True) '--delta', 'none'], check=True)
def update_version(display_version, build):
version = display_version + '-build.' + str(int(build))
numeric_version(version)
return version
def file_version(app): def file_version(app):
import pefile import pefile
with pefile.PE(str(app / 'cutdex.exe')) as pe: with pefile.PE(str(app / 'cutdex.exe')) as pe:
@@ -78,17 +77,6 @@ def file_version(app):
raise ValueError('Missing Flutter display version and build number in PE resources') raise ValueError('Missing Flutter display version and build number in PE resources')
def numeric_version(version):
number = r'(0|[1-9]\d*)'
match = re.fullmatch(rf'{number}\.{number}\.{number}(?:-build\.{number})?', version)
if not match:
raise ValueError('Windows update versions must use major.minor.patch-build.number')
major, minor, patch, build = match.groups()
# SemVer build metadata (+number) does not participate in precedence.
# A numeric prerelease component does, and stable versions rank above it.
return (int(major), int(minor), int(patch), int(build is None), int(build or 0))
def validate_previous(output, package_id, version): def validate_previous(output, package_id, version):
candidate = numeric_version(version) candidate = numeric_version(version)
for feed in output.glob('releases.*.json'): for feed in output.glob('releases.*.json'):
@@ -120,28 +108,32 @@ def verify_manifest(app):
raise ValueError(f'Release checksum mismatch: {name}') raise ValueError(f'Release checksum mismatch: {name}')
def package(args): def package_app(app, output, vpk, *, development=False, require_processing=True):
app, output = args.app.resolve(), args.output.resolve() app, output = Path(app).resolve(), Path(output).resolve()
if output == app or output.is_relative_to(app) or app.is_relative_to(output): if output == app or output.is_relative_to(app) or app.is_relative_to(output):
raise ValueError('Release output must be outside the staged app') raise ValueError('Release output must be outside the staged app')
audit(app) audit(app, require_processing=require_processing)
verify_manifest(app) verify_manifest(app)
sdk_dll = app / 'velopack_libc.dll' sdk_dll = app / 'velopack_libc.dll'
if not sdk_dll.is_file(): if not sdk_dll.is_file():
raise ValueError('Rebuild the app with the Velopack integration before packaging') raise ValueError('Rebuild the app with the Velopack integration before packaging')
command = vpk_command(args.vpk) command = vpk_command(vpk)
check_tool(command) check_tool(command)
version = file_version(app) version = file_version(app)
package_id = 'Cutdex.Dev' if args.development else 'Cutdex' package_id = 'Cutdex.Dev' if development else 'Cutdex'
# The expected identity is compiled into the runner and must match the package. # The updater is generic; verify the host flavor through its PE branding.
identity = package_id.encode('ascii') + b'\0' import pefile
if identity not in (app / 'cutdex.exe').read_bytes(): with pefile.PE(str(app / 'cutdex.exe')) as pe:
products = [table.entries.get(b'ProductName', b'').decode('utf-8')
for group in pe.FileInfo for block in group
if block.Key == b'StringFileInfo' for table in block.StringTable]
if ('Cutdex Dev' if development else 'Cutdex') not in products:
raise ValueError('Package identity does not match the Flutter build flavor') raise ValueError('Package identity does not match the Flutter build flavor')
validate_previous(output, package_id, version) validate_previous(output, package_id, version)
output.mkdir(parents=True, exist_ok=True) output.mkdir(parents=True, exist_ok=True)
pack_release(command, app=app, output=output, package_id=package_id, version=version, pack_release(command, app=app, output=output, package_id=package_id, version=version,
title='Cutdex Dev' if args.development else 'Cutdex') title='Cutdex Dev' if development else 'Cutdex')
print(json.dumps({'version': version, 'packageId': package_id, 'output': str(output)})) return {'version': version, 'packageId': package_id, 'output': str(output)}
def serve(directory, port): def serve(directory, port):
@@ -157,6 +149,7 @@ def serve(directory, port):
def main(): def main():
parser = argparse.ArgumentParser(description=__doc__) parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest='command', required=True) commands = parser.add_subparsers(dest='command', required=True)
commands.add_parser('verify-sdk', help='Verify resolved native SDK before saving a build')
pack = commands.add_parser('pack', help='Package a complete audited release; never uploads') pack = commands.add_parser('pack', help='Package a complete audited release; never uploads')
pack.add_argument('--app', type=Path, required=True) pack.add_argument('--app', type=Path, required=True)
pack.add_argument('--output', type=Path, required=True) pack.add_argument('--output', type=Path, required=True)
@@ -168,7 +161,11 @@ def main():
args = parser.parse_args() args = parser.parse_args()
try: try:
if args.command == 'pack': if args.command == 'pack':
package(args) verify_sdk_version()
print(json.dumps(package_app(args.app, args.output, args.vpk,
development=args.development)))
elif args.command == 'verify-sdk':
print(f'Velopack SDK {verify_sdk_version()} verified')
else: else:
serve(args.directory, args.port) serve(args.directory, args.port)
except KeyboardInterrupt: except KeyboardInterrupt:
-1
View File
@@ -60,7 +60,6 @@ target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX")
# dependencies here. # dependencies here.
target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app dwmapi) target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app dwmapi)
target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")
include("${CMAKE_CURRENT_SOURCE_DIR}/update_configuration.cmake")
# Run the Flutter tool portions of the build. This must not be removed. # Run the Flutter tool portions of the build. This must not be removed.
add_dependencies(${BINARY_NAME} flutter_assemble) add_dependencies(${BINARY_NAME} flutter_assemble)
-18
View File
@@ -1,18 +0,0 @@
# Configuration is baked into the binary; a user's environment cannot redirect it.
set(CUTDEX_WINDOWS_UPDATE_URL "$ENV{CUTDEX_WINDOWS_UPDATE_URL}")
set(CUTDEX_UPDATE_PACKAGE_ID "Cutdex")
set(CUTDEX_UPDATE_TEST_HTTP 0)
if(FLUTTER_APP_FLAVOR STREQUAL "development")
set(CUTDEX_UPDATE_PACKAGE_ID "Cutdex.Dev")
if("$ENV{CUTDEX_UPDATE_TEST_HTTP}" STREQUAL "1")
set(CUTDEX_UPDATE_TEST_HTTP 1)
endif()
endif()
# deskup validates feed URLs; the host limits local HTTP to development.
if(DEFINED ENV{CUTDEX_VELOPACK_ARCHIVE})
set(ENV{DESKUP_VELOPACK_ARCHIVE} "$ENV{CUTDEX_VELOPACK_ARCHIVE}")
endif()
set(DESKUP_WINDOWS_UPDATE_URL "${CUTDEX_WINDOWS_UPDATE_URL}" PARENT_SCOPE)
set(DESKUP_UPDATE_PACKAGE_ID "${CUTDEX_UPDATE_PACKAGE_ID}" PARENT_SCOPE)
set(DESKUP_PREFERENCE_ROOT "Software\\\\Cutdex\\\\" PARENT_SCOPE)
set(DESKUP_ALLOW_LOCAL_HTTP "${CUTDEX_UPDATE_TEST_HTTP}" PARENT_SCOPE)