diff --git a/.github/workflows/publish_companion_pubdev.yml b/.github/workflows/publish_companion_pubdev.yml index 4cc2be4d2..f19a2cfc0 100644 --- a/.github/workflows/publish_companion_pubdev.yml +++ b/.github/workflows/publish_companion_pubdev.yml @@ -66,7 +66,7 @@ jobs: run: | set -euo pipefail package_status="$( - curl -sS -o "$RUNNER_TEMP/pubdev-package.json" -w '%{http_code}' \ + curl -sS --max-time 30 -o "$RUNNER_TEMP/pubdev-package.json" -w '%{http_code}' \ "https://pub.dev/api/packages/$PACKAGE_NAME" )" case "$package_status" in @@ -85,7 +85,7 @@ jobs: esac version_status="$( - curl -sS -o "$RUNNER_TEMP/pubdev-version.json" -w '%{http_code}' \ + curl -sS --max-time 30 -o "$RUNNER_TEMP/pubdev-version.json" -w '%{http_code}' \ "https://pub.dev/api/packages/$PACKAGE_NAME/versions/$PACKAGE_VERSION" )" case "$version_status" in @@ -127,9 +127,24 @@ jobs: --exclude='pubspec_overrides.yaml' \ "$PACKAGE_PATH/" "$RUNNER_TEMP/pub-package/" + # pub.dev serves the package listing with max-age=120, so pub can + # briefly miss the core release_on_prep_merge.yml just saw there. - name: Install dependencies if: steps.publish.outputs.should_publish == 'true' - run: flutter pub get + run: | + set -euo pipefail + attempts=3 + for attempt in $(seq 1 "$attempts"); do + if flutter pub get; then + exit 0 + fi + if [[ "$attempt" -lt "$attempts" ]]; then + echo "flutter pub get failed ($attempt/$attempts); retrying in 60 seconds in case the pub.dev listing is stale." >&2 + sleep 60 + fi + done + echo "flutter pub get failed $attempts times." >&2 + exit 1 working-directory: ${{ runner.temp }}/pub-package - name: Publish - dry run diff --git a/.github/workflows/release_on_prep_merge.yml b/.github/workflows/release_on_prep_merge.yml index 5129cb750..3188ddbf6 100644 --- a/.github/workflows/release_on_prep_merge.yml +++ b/.github/workflows/release_on_prep_merge.yml @@ -83,6 +83,13 @@ jobs: echo "Unsupported release version: $version" >&2 exit 1 fi + # No companion constraint `>=M.m.0 &2 + exit 1 + fi first_heading="$(awk '/^## / {print; exit}' CHANGELOG.md)" if [[ "$first_heading" != "## $version" ]]; then @@ -177,6 +184,7 @@ jobs: wait_for_pub_version() { local package_name="$1" local package_version="$2" + local recovery="$3" local package_url="https://pub.dev/api/packages/$package_name" local attempts="$PUBDEV_WAIT_ATTEMPTS" local interval_seconds="$PUBDEV_WAIT_INTERVAL_SECONDS" @@ -192,6 +200,7 @@ jobs: done echo "$package_name $package_version did not appear on pub.dev." >&2 + echo "$recovery" >&2 exit 1 } @@ -218,7 +227,8 @@ jobs: else push_tag "$CORE_TAG" fi - wait_for_pub_version "llamadart" "$CORE_VERSION" + wait_for_pub_version "llamadart" "$CORE_VERSION" \ + "If the publish_pubdev.yml run for $CORE_TAG failed, rerun it, wait for llamadart $CORE_VERSION on pub.dev, then rerun this workflow." companion_paths=( packages/llamadart_llama_cpp_flutter @@ -240,7 +250,16 @@ jobs: fi companion_tag="$package_name-v$package_version" - if git ls-remote --exit-code --tags origin "refs/tags/$companion_tag" >/dev/null 2>&1; then + companion_tag_sha="$( + git ls-remote --tags origin "refs/tags/$companion_tag" "refs/tags/$companion_tag^{}" | + awk 'END {print $1}' + )" + if [[ -n "$companion_tag_sha" ]]; then + if [[ "$companion_tag_sha" != "$RELEASE_SHA" ]]; then + echo "$companion_tag already exists at $companion_tag_sha, not $RELEASE_SHA, and $package_name $package_version is missing on pub.dev." >&2 + echo "Rerunning that tag's publish_companion_pubdev.yml run would publish the other commit's $package_path, so this commit cannot publish $package_name $package_version: release it from a new release-prep PR that bumps the core version and $package_name's patch version." >&2 + exit 1 + fi echo "$companion_tag already exists, but $package_name $package_version is missing on pub.dev." >&2 echo "If its publish_companion_pubdev.yml run failed transiently, rerun that run, wait for $package_name $package_version on pub.dev, then rerun this workflow." >&2 echo "If the cause is in the repository, this commit cannot publish $package_name $package_version: fix it in a new release-prep PR that bumps the core version and $package_name's patch version." >&2 @@ -248,7 +267,8 @@ jobs: fi push_tag "$companion_tag" - wait_for_pub_version "$package_name" "$package_version" + wait_for_pub_version "$package_name" "$package_version" \ + "If the publish_companion_pubdev.yml run for $companion_tag failed, confirm pub.dev automated publishing is enabled for $package_name with tag pattern $package_name-v{{version}}, rerun that run, wait for $package_name $package_version on pub.dev, then rerun this workflow." done wait_for_github_release "$CORE_TAG" diff --git a/lib/src/backends/stable_diffusion/stable_diffusion_runtime_io.dart b/lib/src/backends/stable_diffusion/stable_diffusion_runtime_io.dart index 82c73e8ab..c1ae1a35f 100644 --- a/lib/src/backends/stable_diffusion/stable_diffusion_runtime_io.dart +++ b/lib/src/backends/stable_diffusion/stable_diffusion_runtime_io.dart @@ -188,14 +188,14 @@ StableDiffusionRuntimeStatus probeStableDiffusionRuntime({ /// lacks, and the Vulkan loader. On iOS and macOS the advice also names the /// `llamadart_stable_diffusion_flutter` companion, which links the runtime /// into the process through Swift Package Manager instead of the hook. -/// [isFlutterTestHost] (default: `FLUTTER_TEST` is set) marks a host +/// [isFlutterTestHost] (default: [isFlutterTestEnvironment]) marks a host /// `flutter test` run, which never links that companion. LlamaUnsupportedException stableDiffusionLoadFailure({ required String platform, required ArgumentError error, List Function(List names) missingWindowsLibraries = findMissingWindowsLibraries, - bool Function() isFlutterTestHost = _isFlutterTestHost, + bool Function() isFlutterTestHost = isFlutterTestEnvironment, }) { final detail = '${error.message ?? error}'; final isApple = platform.startsWith('ios-') || platform.startsWith('macos-'); @@ -312,7 +312,10 @@ const List _windowsVisualCppRuntimeLibraries = [ 'vcruntime140_1.dll', ]; -bool _isFlutterTestHost() => Platform.environment['FLUTTER_TEST'] == 'true'; +/// Whether [environment] (default: this process's) is a host `flutter test` +/// run, which sets `FLUTTER_TEST` to `true`. +bool isFlutterTestEnvironment([Map? environment]) => + (environment ?? Platform.environment)['FLUTTER_TEST'] == 'true'; String _abiLabel(Abi abi) => abi.toString().replaceAll('_', '-'); diff --git a/test/unit/backends/stable_diffusion/stable_diffusion_runtime_io_test.dart b/test/unit/backends/stable_diffusion/stable_diffusion_runtime_io_test.dart index c57d1a78a..be3c92d94 100644 --- a/test/unit/backends/stable_diffusion/stable_diffusion_runtime_io_test.dart +++ b/test/unit/backends/stable_diffusion/stable_diffusion_runtime_io_test.dart @@ -358,6 +358,53 @@ void main() { ); }); + test('detects a flutter test host from FLUTTER_TEST', () { + expect(isFlutterTestEnvironment({'FLUTTER_TEST': 'true'}), isTrue); + expect(isFlutterTestEnvironment({'FLUTTER_TEST': 'false'}), isFalse); + expect(isFlutterTestEnvironment({'FLUTTER_TESTS': 'true'}), isFalse); + expect(isFlutterTestEnvironment(const {}), isFalse); + expect( + isFlutterTestEnvironment(), + Platform.environment['FLUTTER_TEST'] == 'true', + ); + }); + + test('reads FLUTTER_TEST from the process by default', () { + final dir = Directory.systemTemp.createTempSync('sd_flutter_test_host_'); + addTearDown(() => dir.deleteSync(recursive: true)); + final script = File('${dir.path}/load_failure.dart') + ..writeAsStringSync(''' +import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_runtime_io.dart'; + +void main() { + print(stableDiffusionLoadFailure( + platform: 'ios-arm64', + error: ArgumentError("Failed to lookup symbol 'sd_version'"), + ).message); +} +'''); + final packages = File('.dart_tool/package_config.json').absolute.path; + + String messageWith(String flutterTest) { + final result = Process.runSync( + Platform.resolvedExecutable, + ['--packages=$packages', script.path], + environment: {'FLUTTER_TEST': flutterTest}, + ); + expect(result.exitCode, 0, reason: '${result.stderr}'); + return '${result.stdout}'; + } + + expect( + messageWith('true'), + contains('not linked into the flutter test host on ios-arm64'), + ); + expect( + messageWith('false'), + contains('not linked into the process on ios-arm64'), + ); + }); + group('Windows error 126', () { final error126 = ArgumentError( "Couldn't resolve native function 'sd_version' in " diff --git a/test/unit/tooling/companion_pub_preflight_test.dart b/test/unit/tooling/companion_pub_preflight_test.dart index 33cd2ed9c..f75e073a8 100644 --- a/test/unit/tooling/companion_pub_preflight_test.dart +++ b/test/unit/tooling/companion_pub_preflight_test.dart @@ -1,6 +1,7 @@ @TestOn('vm') library; +import 'dart:async'; import 'dart:convert'; import 'dart:io'; @@ -54,7 +55,7 @@ List _publishOrderProblems(String workflow) { multiLine: true, ).allMatches(step).toList(); final coreWait = RegExp( - r'^\s+wait_for_pub_version "llamadart" "\$CORE_VERSION"\s*$', + r'^\s+wait_for_pub_version "llamadart" "\$CORE_VERSION"(?: \\)?$', multiLine: true, ).allMatches(step).toList(); final companionPush = RegExp( @@ -109,6 +110,9 @@ typedef _Fetch = Future Function(Uri uri); name: 'llamadart_llama_cpp_flutter', path: 'packages/llamadart_llama_cpp_flutter', ); + File( + '${root.path}/${companion.path}/darwin/${companion.name}/Package.swift', + ).createSync(recursive: true); File('${root.path}/${companion.path}/pubspec.yaml') ..parent.createSync(recursive: true) ..writeAsStringSync( @@ -330,27 +334,208 @@ void main() { expect(steps, contains('already released')); }); - test('the preflight CLI runs the published-constraint check', () { - final source = File( - 'tool/release/companion_pub_preflight.dart', - ).readAsStringSync().replaceAll('\r\n', '\n'); - final wired = RegExp( - r'final problems = \[[\s\S]*?\.\.\.await ' - r'companionPublishedConstraintProblems\(\s*Directory\.current,\s*' - r'companions,\s*_httpGet,?\s*\),[\s\S]*?\];\s*' - r'if \(problems\.isNotEmpty\) \{', - ); + group('runCompanionPubPreflight', () { + /// Answers the package listing with [listing] and the version with + /// [version], recording each [Uri] asked in [asked]. + _Fetch pubDev({ + int listing = HttpStatus.ok, + PubDevResponse version = (status: HttpStatus.notFound, body: ''), + List? asked, + }) => (uri) async { + asked?.add(uri); + return uri.pathSegments.contains('versions') + ? version + : (status: listing, body: '{}'); + }; + + Future<({int code, String out, String err})> run( + Directory root, + _Fetch get, + ) async { + final out = StringBuffer(); + final err = StringBuffer(); + final code = await runCompanionPubPreflight( + root, + get, + out: out, + err: err, + ); + return (code: code, out: '$out', err: '$err'); + } - expect(wired.hasMatch(source), isTrue); - expect( - wired.hasMatch( - source.replaceFirst( - 'companionPublishedConstraintProblems(\n Directory.current,', - 'companionPublishedConstraintProblems(\n Directory.systemTemp,', + test('passes when both checks pass', () async { + final repo = _repo(); + final asked = []; + + final result = await run(repo.root, pubDev(asked: asked)); + + expect(result.code, 0); + expect(result.err, isEmpty); + expect(result.out, contains('llamadart_llama_cpp_flutter')); + expect(asked, [ + Uri.parse('https://pub.dev/api/packages/llamadart_llama_cpp_flutter'), + Uri.parse( + 'https://pub.dev/api/packages/llamadart_llama_cpp_flutter/' + 'versions/0.0.24', + ), + ]); + }); + + test('fails on a package missing from pub.dev', () async { + final result = await run( + _repo().root, + pubDev(listing: HttpStatus.notFound), + ); + + expect(result.code, 1); + expect( + result.err, + allOf( + startsWith('Companion pub.dev preflight failed:'), + contains('does not exist on pub.dev yet'), + ), + ); + }); + + test('fails on a published version with another constraint', () async { + final result = await run( + _repo().root, + pubDev(version: await _published('>=0.12.0 <0.13.0')(Uri())), + ); + + expect(result.code, 1); + expect(result.err, contains('bump llamadart_llama_cpp_flutter past')); + }); + + test('fails without companions', () async { + final root = Directory.systemTemp.createTempSync('companion_preflight_'); + addTearDown(() => root.deleteSync(recursive: true)); + + final result = await run(root, pubDev()); + + expect(result.code, 1); + expect(result.err, contains('No Flutter Apple companion packages')); + }); + }); + + group('getWithOneRetry', () { + const ok = (status: HttpStatus.ok, body: 'ok'); + final uri = Uri.parse('https://pub.dev/api/packages/companion'); + + Future<(PubDevResponse, int)> fetch(List answers) async { + var calls = 0; + final response = await getWithOneRetry(uri, (asked) async { + expect(asked, uri); + final answer = answers[calls++]; + if (answer is Exception) throw answer; + return answer as PubDevResponse; + }, retryDelay: Duration.zero); + return (response, calls); + } + + test('does not retry an answer below 500', () async { + expect(await fetch([ok]), (ok, 1)); + const missing = (status: HttpStatus.notFound, body: ''); + expect(await fetch([missing]), (missing, 1)); + }); + + test('retries a stalled body or a 5xx answer once', () async { + expect(await fetch([TimeoutException('body'), ok]), (ok, 2)); + expect(await fetch([const SocketException('reset'), ok]), (ok, 2)); + expect( + await fetch([(status: HttpStatus.serviceUnavailable, body: ''), ok]), + (ok, 2), + ); + }); + + test('reports a second failure', () async { + const unavailable = (status: HttpStatus.badGateway, body: ''); + expect(await fetch([unavailable, unavailable]), (unavailable, 2)); + await expectLater( + fetch([TimeoutException('first'), TimeoutException('second')]), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'second', + ), ), + ); + }); + }); + + test('pubDevGet times out a body that stalls after its headers', () async { + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + addTearDown(() => server.close(force: true)); + server.listen((request) async { + request.response + ..contentLength = 1024 + ..write('{"versions":'); + await request.response.flush(); + }); + + await expectLater( + pubDevGet( + Uri.http('127.0.0.1:${server.port}', '/api/packages/companion'), + bodyTimeout: const Duration(milliseconds: 200), ), - isFalse, + throwsA(isA()), ); + }, timeout: const Timeout(Duration(seconds: 20))); + + group('the preflight CLI', () { + const script = 'tool/release/companion_pub_preflight.dart'; + + ProcessResult runCli(List arguments) { + final cwd = Directory.systemTemp.createTempSync('companion_preflight_'); + addTearDown(() => cwd.deleteSync(recursive: true)); + return Process.runSync(Platform.resolvedExecutable, [ + '--packages=${File('.dart_tool/package_config.json').absolute.path}', + File(script).absolute.path, + ...arguments, + ], workingDirectory: cwd.path); + } + + test('exits with the preflight result for the current directory', () { + final result = runCli(const []); + + expect(result.exitCode, 1, reason: '${result.stderr}'); + expect( + '${result.stderr}', + contains('No Flutter Apple companion packages found under packages/.'), + ); + }); + + test('rejects arguments', () { + expect(runCli(const ['--release-prep']).exitCode, 64); + }); + + test('fetches pub.dev with one retry', () { + final source = File(script).readAsStringSync().replaceAll('\r\n', '\n'); + final wired = RegExp( + r'exitCode = await runCompanionPubPreflight\(\s*Directory\.current,\s*' + r'\(uri\) => getWithOneRetry\(uri, pubDevGet\),', + ); + + expect(wired.hasMatch(source), isTrue); + for (final mutated in [ + source.replaceFirst( + '(uri) => getWithOneRetry(uri, pubDevGet)', + 'pubDevGet', + ), + source.replaceFirst( + 'exitCode = await runCompanionPubPreflight(', + 'await runCompanionPubPreflight(', + ), + source.replaceFirst( + 'runCompanionPubPreflight(\n Directory.current,', + 'runCompanionPubPreflight(\n Directory.systemTemp,', + ), + ]) { + expect(mutated, isNot(source)); + expect(wired.hasMatch(mutated), isFalse); + } + }); }); test('the release workflow publishes the core before any companion', () { @@ -365,11 +550,14 @@ void main() { final workflow = File( '.github/workflows/release_on_prep_merge.yml', ).readAsStringSync().replaceAll('\r\n', '\n'); - const coreBlock = - ' wait_for_pub_version "llamadart" "\$CORE_VERSION"\n'; - const companionWait = - ' wait_for_pub_version "\$package_name" "\$package_version"\n' - ' done\n'; + final coreBlock = RegExp( + r'^ +wait_for_pub_version "llamadart" .*\\\n.*\n', + multiLine: true, + ).firstMatch(workflow)![0]!; + final companionWait = RegExp( + r'^ +wait_for_pub_version "\$package_name" .*\\\n.*\n +done\n', + multiLine: true, + ).firstMatch(workflow)![0]!; for (final mutated in [ workflow diff --git a/test/unit/tooling/companion_release_workflow_scripts_test.dart b/test/unit/tooling/companion_release_workflow_scripts_test.dart index f4032ac57..299099c38 100644 --- a/test/unit/tooling/companion_release_workflow_scripts_test.dart +++ b/test/unit/tooling/companion_release_workflow_scripts_test.dart @@ -34,7 +34,12 @@ YamlMap _step(String workflow, String job, String name) { /// Commands the workflow scripts call, replaced by stubs that log every call /// to `$STUB_LOG` and answer from files under `$STUB_STATE`. const _stubs = { - 'dart': 'exit 0\n', + 'dart': r''' +if [[ -f "$STUB_STATE/dart_failures" ]] && grep -Fxq "$2" "$STUB_STATE/dart_failures"; then + exit 1 +fi +''', + 'sleep': '', 'gh': r''' if [[ "$1" == release ]]; then exit 0 @@ -46,6 +51,14 @@ case "$1" in echo "$STUB_HEAD" ;; ls-remote) + if [[ -f "$STUB_STATE/ls_remote_failures" ]]; then + for arg in "$@"; do + if grep -Fxq -- "$arg" "$STUB_STATE/ls_remote_failures"; then + echo "fatal: unable to access origin" >&2 + exit 128 + fi + done + fi found=false for arg in "$@"; do [[ "$arg" == refs/tags/* ]] || continue @@ -68,13 +81,38 @@ esac 'curl': r''' url="${*: -1}" body="$STUB_STATE/pub/${url//[!A-Za-z0-9]/_}" -if [[ -f "$body" ]]; then +out="" +write_out="" +while [[ $# -gt 0 ]]; do + case "$1" in + -o) out="$2"; shift ;; + -w) write_out="$2"; shift ;; + esac + shift +done +if [[ -n "$write_out" ]]; then + if [[ -f "$body" ]]; then + cat "$body" > "$out" + echo 200 + else + echo '{}' > "$out" + echo 404 + fi +elif [[ -f "$body" ]]; then cat "$body" else exit 22 fi ''', 'flutter': r''' +failures="$STUB_STATE/pub_get_failures" +if [[ "$1 $2" == "pub get" && -f "$failures" ]]; then + left="$(cat "$failures")" + if (( left > 0 )); then + echo "$((left - 1))" > "$failures" + exit 1 + fi +fi { echo "pwd=$PWD" if [[ -f pubspec_overrides.yaml ]]; then @@ -123,6 +161,11 @@ class _Sandbox { '$state/remote_tags', ).writeAsStringSync('$sha $ref\n', mode: FileMode.append); + /// Makes `git ls-remote` exit 128 whenever it is asked for [ref]. + void lsRemoteFails(String ref) => File( + '$state/ls_remote_failures', + ).writeAsStringSync('$ref\n', mode: FileMode.append); + void pub(String url, String body) => File( '$state/pub/${url.replaceAll(RegExp('[^A-Za-z0-9]'), '_')}', ).writeAsStringSync(body); @@ -131,17 +174,24 @@ class _Sandbox { ..parent.createSync(recursive: true) ..writeAsStringSync(contents); - /// Runs [script] the way Actions runs a `shell: bash` step. + /// Runs [step]'s script the way Actions runs it on Linux: `shell: bash` + /// adds `-o pipefail` to the default `bash -e`. ProcessResult run( - String script, { + YamlMap step, { required String workingDirectory, Map env = const {}, }) { final path = '$root/step.sh'; - File(path).writeAsStringSync(script); + File(path).writeAsStringSync('${step['run']}'); return Process.runSync( 'bash', - ['--noprofile', '--norc', '-eo', 'pipefail', path], + [ + '--noprofile', + '--norc', + '-e', + if (step['shell'] == 'bash') ...['-o', 'pipefail'], + path, + ], workingDirectory: workingDirectory, environment: { 'PATH': '$bin:${Platform.environment['PATH']}', @@ -188,17 +238,45 @@ Map _outputs(String path) => { ), }; -/// Remote state for one release run of core `0.13.0`. +/// Remote state for one release run of core `0.13.0`, unless [version] +/// names another core; [failingDart] lists the `dart run` scripts that fail. typedef _Release = ({ String name, void Function(_Sandbox sandbox) remote, Set missingCompanions, + String? version, + Set failingDart, }); +/// A [_Release] of core `0.13.0` whose `dart run` scripts all pass. +_Release _release( + String name, { + void Function(_Sandbox sandbox)? remote, + Set missingCompanions = const {}, +}) => ( + name: name, + remote: remote ?? (_) {}, + missingCompanions: missingCompanions, + version: null, + failingDart: const {}, +); + const _coreListing = 'https://pub.dev/api/packages/llamadart'; +const _preflightScript = 'tool/release/companion_pub_preflight.dart'; +const _verifierScript = 'tool/testing/verify_release_docs_versions.dart'; + +/// Whether Actions keeps running the job's later steps after [step] fails. +bool _continuesOnError(YamlMap step) => + step['continue-on-error'] != null && step['continue-on-error'] != false; + +/// Whether [step]'s `if` overrides the implicit `success()` that skips it +/// after an earlier step failed. +bool _runsAfterFailure(YamlMap step) => + RegExp(r'\b(always|failure|cancelled)\(\)').hasMatch('${step['if']}'); /// Runs the release workflow's validation and publication steps from /// [workflow] against [release], and returns the step results and calls. +/// Publication runs after a failed validation only when Actions would run it. ({ ProcessResult validate, ProcessResult? publish, @@ -207,12 +285,16 @@ const _coreListing = 'https://pub.dev/api/packages/llamadart'; List problems, }) _runRelease(String workflow, _Release release) { + final version = release.version ?? '0.13.0'; final sandbox = _Sandbox(); final repo = '${sandbox.root}/repo'; sandbox - ..file('repo/pubspec.yaml', 'name: llamadart\nversion: 0.13.0\n') - ..file('repo/CHANGELOG.md', '## 0.13.0\n\n- Release.\n') - ..pub(_coreListing, '{"versions":[{"version":"0.13.0"}]}'); + ..file('repo/pubspec.yaml', 'name: llamadart\nversion: $version\n') + ..file('repo/CHANGELOG.md', '## $version\n\n- Release.\n') + ..pub(_coreListing, '{"versions":[{"version":"$version"}]}'); + File( + '${sandbox.state}/dart_failures', + ).writeAsStringSync(release.failingDart.map((script) => '$script\n').join()); for (final companion in _companions) { sandbox.file( 'repo/packages/$companion/pubspec.yaml', @@ -228,14 +310,21 @@ _runRelease(String workflow, _Release release) { final problems = []; final validateStep = _step(workflow, 'release', 'Validate release state'); + final publishStep = _step( + workflow, + 'release', + 'Publish core tag and companion packages', + ); final githubOutput = '${sandbox.root}/validate_output'; File(githubOutput).createSync(); final validate = sandbox.run( - '${validateStep['run']}', + validateStep, workingDirectory: repo, env: {'GITHUB_OUTPUT': githubOutput}, ); - if (validate.exitCode != 0) { + if (validate.exitCode != 0 && + !_continuesOnError(validateStep) && + !_runsAfterFailure(publishStep)) { return ( validate: validate, publish: null, @@ -245,20 +334,15 @@ _runRelease(String workflow, _Release release) { ); } - final publishStep = _step( - workflow, - 'release', - 'Publish core tag and companion packages', - ); final resolved = _resolveEnv(publishStep, { for (final output in _outputs(githubOutput).entries) 'steps.${validateStep['id']}.outputs.${output.key}': output.value, 'github.token': 'github-token', 'secrets.RELEASE_AUTOMATION_TOKEN': 'release-token', }); - problems.addAll(resolved.problems); + if (validate.exitCode == 0) problems.addAll(resolved.problems); final publish = sandbox.run( - '${publishStep['run']}', + publishStep, workingDirectory: repo, env: { ...resolved.env, @@ -278,6 +362,19 @@ _runRelease(String workflow, _Release release) { ); } +/// Why any of [steps] in [workflow]'s [job] could keep going past a failed +/// command: each script must start with `set -euo pipefail`. +List _strictShellProblems( + String workflow, + String job, + List steps, +) => [ + for (final name in steps) + if ('${_step(workflow, job, name)['run']}'.trimLeft().split('\n').first != + 'set -euo pipefail') + '$name must start with set -euo pipefail', +]; + bool _pushed(List calls, String tag) => calls.any( (call) => call.startsWith('gh api') && @@ -285,19 +382,22 @@ bool _pushed(List calls, String tag) => calls.any( call.contains('sha=$_releaseSha'), ); +bool _pushedAnyTag(List calls) => calls.any( + (call) => call.startsWith('gh api') && call.contains('ref=refs/tags/'), +); + /// Why [workflow] could push the core tag twice, resume at another commit or -/// leave a companion half-published without saying how to recover. +/// leave a core or companion half-published without saying how to recover. List _releaseResumeProblems(String workflow) { final problems = []; void check(bool ok, String problem) { if (!ok) problems.add(problem); } - final fresh = _runRelease(workflow, ( - name: 'fresh', - remote: (_) {}, - missingCompanions: {_companions.first}, - )); + final fresh = _runRelease( + workflow, + _release('fresh', missingCompanions: {_companions.first}), + ); problems.addAll(fresh.problems); check( fresh.validate.exitCode == 0 && fresh.publish?.exitCode == 0, @@ -326,17 +426,15 @@ List _releaseResumeProblems(String workflow) { ); for (final resume in <_Release>[ - ( - name: 'lightweight tag at the release commit', + _release( + 'lightweight tag at the release commit', remote: (sandbox) => sandbox.remoteTag(_releaseSha, 'refs/tags/v0.13.0'), - missingCompanions: const {}, ), - ( - name: 'annotated tag at the release commit', + _release( + 'annotated tag at the release commit', remote: (sandbox) => sandbox ..remoteTag(_tagObjectSha, 'refs/tags/v0.13.0') ..remoteTag(_releaseSha, 'refs/tags/v0.13.0^{}'), - missingCompanions: const {}, ), ]) { final run = _runRelease(workflow, resume); @@ -356,11 +454,13 @@ List _releaseResumeProblems(String workflow) { ); } - final moved = _runRelease(workflow, ( - name: 'tag at another commit', - remote: (sandbox) => sandbox.remoteTag(_otherSha, 'refs/tags/v0.13.0'), - missingCompanions: const {}, - )); + final moved = _runRelease( + workflow, + _release( + 'tag at another commit', + remote: (sandbox) => sandbox.remoteTag(_otherSha, 'refs/tags/v0.13.0'), + ), + ); check( moved.validate.exitCode != 0 && '${moved.validate.stderr}'.contains( @@ -373,23 +473,307 @@ List _releaseResumeProblems(String workflow) { 'a core tag at another commit must not reach publication', ); - final halfPublished = _runRelease(workflow, ( - name: 'companion tag without a pub.dev version', - remote: (sandbox) => sandbox - ..remoteTag(_releaseSha, 'refs/tags/v0.13.0') - ..remoteTag(_releaseSha, 'refs/tags/${_companions[1]}-v0.13.0'), - missingCompanions: {_companions[1]}, + final companionTag = 'refs/tags/${_companions[1]}-v0.13.0'; + for (final halfPublished in <_Release>[ + _release( + 'lightweight companion tag at the release commit', + remote: (sandbox) => sandbox + ..remoteTag(_releaseSha, 'refs/tags/v0.13.0') + ..remoteTag(_releaseSha, companionTag), + missingCompanions: {_companions[1]}, + ), + _release( + 'annotated companion tag at the release commit', + remote: (sandbox) => sandbox + ..remoteTag(_releaseSha, 'refs/tags/v0.13.0') + ..remoteTag(_tagObjectSha, companionTag) + ..remoteTag(_releaseSha, '$companionTag^{}'), + missingCompanions: {_companions[1]}, + ), + ]) { + final run = _runRelease(workflow, halfPublished); + final stderr = '${run.publish?.stderr}'; + check( + run.publish != null && + run.publish!.exitCode != 0 && + stderr.contains('rerun that run') && + stderr.contains('publish_companion_pubdev.yml') && + stderr.contains('bumps the core version') && + !stderr.contains('already exists at'), + 'a ${halfPublished.name} without its pub.dev version must stop with ' + 'both recovery paths: $stderr', + ); + check( + !run.calls.any((call) => call.contains('ref=$companionTag ')), + 'a ${halfPublished.name} must not be pushed again', + ); + } + + final strayCompanion = _runRelease( + workflow, + _release( + 'companion tag at another commit', + remote: (sandbox) => sandbox + ..remoteTag(_releaseSha, 'refs/tags/v0.13.0') + ..remoteTag(_tagObjectSha, companionTag) + ..remoteTag(_otherSha, '$companionTag^{}'), + missingCompanions: {_companions[1]}, + ), + ); + final strayStderr = '${strayCompanion.publish?.stderr}'; + check( + strayCompanion.publish != null && + strayCompanion.publish!.exitCode != 0 && + strayStderr.contains( + '${_companions[1]}-v0.13.0 already exists at $_otherSha, not ' + '$_releaseSha', + ) && + strayStderr.contains('bumps the core version') && + !strayStderr.contains('rerun that run'), + 'a companion tag at another commit must stop without advising a rerun ' + 'that would publish that commit: $strayStderr', + ); + check( + !strayCompanion.calls.any((call) => call.contains('ref=$companionTag ')), + 'a companion tag at another commit must not be pushed again', + ); + + final coreMissing = _runRelease( + workflow, + _release( + 'core publish failure', + remote: (sandbox) => sandbox + ..remoteTag(_releaseSha, 'refs/tags/v0.13.0') + ..pub(_coreListing, '{"versions":[{"version":"0.12.9"}]}'), + ), + ); + final coreStderr = '${coreMissing.publish?.stderr}'; + check( + coreMissing.publish != null && + coreMissing.publish!.exitCode != 0 && + coreStderr.contains('llamadart 0.13.0 did not appear on pub.dev') && + coreStderr.contains('publish_pubdev.yml run for v0.13.0 failed') && + !_pushedAnyTag(coreMissing.calls), + 'a core missing from pub.dev must stop before any companion and name ' + 'publish_pubdev.yml: $coreStderr', + ); + + final companionMissing = _runRelease( + workflow, + _release( + 'companion publish failure', + remote: (sandbox) => sandbox.pub( + 'https://pub.dev/api/packages/${_companions.first}', + '{"versions":[{"version":"0.0.24"}]}', + ), + missingCompanions: {_companions.first}, + ), + ); + final companionStderr = '${companionMissing.publish?.stderr}'; + check( + companionMissing.publish != null && + companionMissing.publish!.exitCode != 0 && + companionStderr.contains( + 'publish_companion_pubdev.yml run for ${_companions.first}-v0.13.0 ' + 'failed', + ) && + companionStderr.contains('automated publishing is enabled'), + 'a companion missing from pub.dev after its tag must name its publish ' + 'run and automated publishing: $companionStderr', + ); + return problems; +} + +/// Why [workflow] could push a tag for a prerelease core, or after the +/// release verifier or companion preflight failed. +List _releaseGuardProblems(String workflow) { + final problems = [ + ..._strictShellProblems(workflow, 'release', [ + 'Check release-prep gate', + 'Validate release state', + 'Publish core tag and companion packages', + ]), + ]; + void check(bool ok, String problem) { + if (!ok) problems.add(problem); + } + + final prerelease = _runRelease(workflow, ( + name: 'prerelease core', + remote: (_) {}, + missingCompanions: const {}, + version: '0.13.0-dev.1', + failingDart: const {}, )); - final stderr = '${halfPublished.publish?.stderr}'; check( - halfPublished.publish != null && - halfPublished.publish!.exitCode != 0 && - stderr.contains('rerun that run') && - stderr.contains('publish_companion_pubdev.yml') && - stderr.contains('bumps the core version'), - 'a companion tag without its pub.dev version must stop with both ' - 'recovery paths: $stderr', + prerelease.validate.exitCode != 0 && + '${prerelease.validate.stderr}'.contains( + 'publishes only stable core versions, but pubspec.yaml is the ' + 'prerelease 0.13.0-dev.1', + ) && + !prerelease.calls.any((call) => call.startsWith('dart ')) && + prerelease.publish == null && + !_pushedAnyTag(prerelease.calls), + 'a prerelease core must stop before the verifier and any tag: ' + '${prerelease.validate.stderr}${prerelease.publish?.stderr}', ); + + final buildMetadata = _runRelease(workflow, ( + name: 'core with build metadata', + remote: (_) {}, + missingCompanions: const {}, + version: '0.13.0+build-1', + failingDart: const {}, + )); + problems.addAll(buildMetadata.problems); + check( + buildMetadata.validate.exitCode == 0 && + buildMetadata.publish?.exitCode == 0 && + _pushed(buildMetadata.calls, 'v0.13.0+build-1'), + 'a core with build metadata is not a prerelease and must publish: ' + '${buildMetadata.validate.stderr}${buildMetadata.publish?.stderr}', + ); + + for (final script in [_verifierScript, _preflightScript]) { + final run = _runRelease(workflow, ( + name: 'failing $script', + remote: (_) {}, + missingCompanions: const {}, + version: null, + failingDart: {script}, + )); + check( + run.calls.contains('dart run $script') || + run.calls.any((call) => call.startsWith('dart run $script ')), + 'release validation must run $script', + ); + check( + run.validate.exitCode != 0 && + run.publish == null && + !_pushedAnyTag(run.calls), + 'a failing $script must stop the release before any tag: ' + '${run.validate.stderr}${run.publish?.stderr}', + ); + } + + final unreachableCore = _runRelease( + workflow, + _release( + 'unreachable core tag lookup', + remote: (sandbox) => sandbox.lsRemoteFails('refs/tags/v0.13.0'), + ), + ); + check( + unreachableCore.validate.exitCode != 0 && + unreachableCore.publish == null && + !unreachableCore.output.contains('core_tag_exists=') && + !_pushedAnyTag(unreachableCore.calls), + 'a failed core tag lookup must stop the release before any tag: ' + '${unreachableCore.validate.stderr}${unreachableCore.publish?.stderr}', + ); + + final companionTag = 'refs/tags/${_companions[1]}-v0.13.0'; + final unreachableCompanion = _runRelease( + workflow, + _release( + 'unreachable companion tag lookup', + remote: (sandbox) => sandbox + ..remoteTag(_releaseSha, 'refs/tags/v0.13.0') + ..lsRemoteFails(companionTag), + missingCompanions: {_companions[1]}, + ), + ); + check( + unreachableCompanion.validate.exitCode == 0 && + unreachableCompanion.publish != null && + unreachableCompanion.publish!.exitCode != 0 && + !_pushedAnyTag(unreachableCompanion.calls), + 'a failed companion tag lookup must stop before pushing the companion: ' + '${unreachableCompanion.validate.stderr}' + '${unreachableCompanion.publish?.stderr}', + ); + return problems; +} + +/// Why [workflow]'s pub.dev checks could hang or misread a missing version. +List _companionDecideProblems(String workflow) { + final problems = [ + ..._strictShellProblems(workflow, 'publish-companion', [ + 'Resolve package from tag', + 'Decide whether to publish', + 'Install dependencies', + ]), + ]; + final step = _step( + workflow, + 'publish-companion', + 'Decide whether to publish', + ); + final resolved = _resolveEnv(step, { + 'steps.package.outputs.name': 'companion', + 'steps.package.outputs.version': '0.13.1', + }); + problems.addAll(resolved.problems); + for (final published in [false, true]) { + final sandbox = _Sandbox(); + sandbox.pub('https://pub.dev/api/packages/companion', '{}'); + if (published) { + sandbox.pub( + 'https://pub.dev/api/packages/companion/versions/0.13.1', + '{}', + ); + } + final runnerTemp = '${sandbox.root}/runner'; + Directory(runnerTemp).createSync(); + final output = '${sandbox.root}/output'; + File(output).createSync(); + final result = sandbox.run( + step, + workingDirectory: sandbox.root, + env: { + ...resolved.env, + 'RUNNER_TEMP': runnerTemp, + 'GITHUB_OUTPUT': output, + }, + ); + final curls = sandbox.calls.where((call) => call.startsWith('curl ')); + if (result.exitCode != 0 || + _outputs(output)['should_publish'] != '${!published}') { + problems.add( + 'a ${published ? 'published' : 'missing'} version must set ' + 'should_publish=${!published}: ${result.stderr}', + ); + } + if (curls.length != 2 || + !curls.every((call) => call.contains('--max-time '))) { + problems.add('every pub.dev request must set --max-time'); + } + } + return problems; +} + +/// Why [workflow]'s dependency install could fail on a pub.dev listing that +/// is still stale, or retry without end. +List _companionInstallProblems(String workflow) { + final problems = []; + final step = _step(workflow, 'publish-companion', 'Install dependencies'); + for (final (failures, succeeds) in [(0, true), (2, true), (3, false)]) { + final sandbox = _Sandbox(); + File('${sandbox.state}/pub_get_failures').writeAsStringSync('$failures'); + final result = sandbox.run(step, workingDirectory: sandbox.root); + final pubGets = sandbox.calls.where((call) => call == 'flutter pub get'); + final sleeps = sandbox.calls.where((call) => call == 'sleep 60'); + final attempts = succeeds ? failures + 1 : 3; + if ((result.exitCode == 0) != succeeds || + pubGets.length != attempts || + sleeps.length != attempts - 1) { + problems.add( + '$failures failed flutter pub get runs must take $attempts attempts ' + 'and ${succeeds ? 'succeed' : 'fail'}; ran ${pubGets.length}, slept ' + '${sleeps.length} times, exit ${result.exitCode}: ${result.stderr}', + ); + } + } return problems; } @@ -418,7 +802,7 @@ List _companionPublishProblems(String workflow) { }); problems.addAll(resolved.problems); final result = sandbox.run( - '${prepare['run']}', + prepare, workingDirectory: '${sandbox.root}/checkout', env: {...resolved.env, 'RUNNER_TEMP': runnerTemp}, ); @@ -473,7 +857,7 @@ List _ciDryRunProblems(String workflow) { problems.add('the dry-run must start in the companion package'); } final result = sandbox.run( - '${step['run']}', + step, workingDirectory: package, env: {'RUNNER_TEMP': runnerTemp, 'GITHUB_WORKSPACE': workspace}, ); @@ -546,6 +930,30 @@ void main() { RegExp(r'^.*rerun that run.*\n', multiLine: true), '', ), + 'trusts a companion tag at another commit': (source) => + source.replaceFirst( + 'if [[ "\$companion_tag_sha" != "\$RELEASE_SHA" ]]; then', + 'if false; then', + ), + 'reads the companion tag object, not its commit': (source) => + source.replaceFirst(' "refs/tags/\$companion_tag^{}"', ''), + 'pushes a companion tag that already exists': (source) => + source.replaceFirst( + 'if [[ -n "\$companion_tag_sha" ]]; then', + 'if false; then', + ), + 'no recovery for a core publish failure': (source) => + source.replaceFirst( + 'If the publish_pubdev.yml run for \$CORE_TAG failed, ', + '', + ), + 'no automated publishing hint for a companion': (source) => + source.replaceFirst( + 'confirm pub.dev automated publishing is enabled for ' + '\$package_name with tag pattern ' + '\$package_name-v{{version}}, ', + '', + ), }; for (final mutation in mutations.entries) { final mutated = mutation.value(workflow); @@ -557,6 +965,74 @@ void main() { ); } }); + + test('stops a prerelease core or a failed check before any tag', () { + expect(_releaseGuardProblems(workflow), isEmpty); + }); + + test('rejects a bypassed release guard', () { + const preflight = 'dart run $_preflightScript\n'; + final mutations = { + 'accepts a prerelease core': (source) => source.replaceFirst( + 'if [[ "\${version%%+*}" == *-* ]]; then', + 'if false; then', + ), + 'treats build metadata as a prerelease': (source) => source + .replaceFirst('"\${version%%+*}" == *-*', '"\$version" == *[-+]*'), + 'skips the companion preflight': (source) => source.replaceFirst( + ' $preflight', + ' if false; then\n $preflight fi\n', + ), + 'ignores a failed companion preflight': (source) => source.replaceFirst( + preflight, + 'dart run $_preflightScript || true\n', + ), + 'ignores a failed release verifier': (source) => source.replaceFirst( + 'dart run $_verifierScript --release-prep\n', + 'dart run $_verifierScript --release-prep || true\n', + ), + 'continues past a failed validation': (source) => source.replaceFirst( + ' id: release\n', + ' id: release\n continue-on-error: true\n', + ), + 'publishes after a failed validation': (source) => source.replaceFirst( + " - name: Publish core tag and companion packages\n" + " if: steps.gate.outputs.should_release == 'true'\n", + " - name: Publish core tag and companion packages\n" + " if: \${{ always() && steps.gate.outputs.should_release == 'true' }}\n", + ), + 'validates without set -euo pipefail': (source) => source.replaceFirst( + ' set -euo pipefail\n\n version=', + ' version=', + ), + 'publishes without set -euo pipefail': (source) => source.replaceFirst( + ' set -euo pipefail\n\n if [[ -z "\${RELEASE_TOKEN:-}" ]]', + ' if [[ -z "\${RELEASE_TOKEN:-}" ]]', + ), + 'ignores a failed core tag lookup': (source) => source.replaceFirst( + ' git ls-remote --tags origin "refs/tags/\$core_tag" ' + '"refs/tags/\$core_tag^{}" |\n', + ' { git ls-remote --tags origin "refs/tags/\$core_tag" ' + '"refs/tags/\$core_tag^{}" || true; } |\n', + ), + 'ignores a failed companion tag lookup': (source) => source.replaceFirst( + ' git ls-remote --tags origin ' + '"refs/tags/\$companion_tag" "refs/tags/\$companion_tag^{}" |\n', + ' { git ls-remote --tags origin ' + '"refs/tags/\$companion_tag" "refs/tags/\$companion_tag^{}" ' + '|| true; } |\n', + ), + }; + for (final mutation in mutations.entries) { + final mutated = mutation.value(workflow); + expect(mutated, isNot(workflow), reason: mutation.key); + expect( + _releaseGuardProblems(mutated), + isNotEmpty, + reason: mutation.key, + ); + } + }); }, skip: Platform.isWindows ? _posixOnly : false); group('publish_companion_pubdev.yml', () { @@ -566,6 +1042,44 @@ void main() { expect(_companionPublishProblems(workflow), isEmpty); }); + test('bounds pub.dev requests and retries a stale listing', () { + expect(_companionDecideProblems(workflow), isEmpty); + expect(_companionInstallProblems(workflow), isEmpty); + }); + + test('rejects unbounded or unretried pub.dev access', () { + final decide = { + 'pub.dev requests without --max-time': (source) => + source.replaceAll('curl -sS --max-time 30 ', 'curl -sS '), + 'decides without set -euo pipefail': (source) => source.replaceFirst( + ' set -euo pipefail\n package_status=', + ' package_status=', + ), + }; + final install = { + 'no flutter pub get retry': (source) => + source.replaceFirst('attempts=3\n', 'attempts=1\n'), + 'retries without a pause': (source) => + source.replaceFirst(' sleep 60\n', ''), + 'reports success after every attempt failed': (source) => + source.replaceFirst( + ' echo "flutter pub get failed \$attempts times." >&2\n' + ' exit 1\n', + '', + ), + }; + for (final (mutations, problems) in [ + (decide, _companionDecideProblems), + (install, _companionInstallProblems), + ]) { + for (final mutation in mutations.entries) { + final mutated = mutation.value(workflow); + expect(mutated, isNot(workflow), reason: mutation.key); + expect(problems(mutated), isNotEmpty, reason: mutation.key); + } + } + }); + test('rejects a publish that keeps the checkout override', () { final mutations = { 'W5 copies pubspec_overrides.yaml': (source) => source.replaceFirst( diff --git a/test/unit/tooling/verify_release_docs_companion_core_constraint_test.dart b/test/unit/tooling/verify_release_docs_companion_core_constraint_test.dart index 0e69137a4..3151e04ac 100644 --- a/test/unit/tooling/verify_release_docs_companion_core_constraint_test.dart +++ b/test/unit/tooling/verify_release_docs_companion_core_constraint_test.dart @@ -240,6 +240,26 @@ void main() { ); } }); + + test('names a prerelease core instead of a window that excludes it', () { + final root = _tempRoot(); + _writeCompanions(root); + + final errors = checkCompanionCoreConstraints( + root, + Version.parse('0.13.0-dev.1'), + ); + + expect(errors, hasLength(companionSwiftPins.length)); + expect( + errors.first, + allOf( + contains('but core is the prerelease 0.13.0-dev.1'), + contains('publishes only stable core versions'), + isNot(contains("`'>=0.13.0 <0.14.0'` for a new minor")), + ), + ); + }); }); group('checkPublishedCompanionPins', () { diff --git a/tool/release/companion_pub_preflight.dart b/tool/release/companion_pub_preflight.dart index bd3187552..936f1fe70 100644 --- a/tool/release/companion_pub_preflight.dart +++ b/tool/release/companion_pub_preflight.dart @@ -17,6 +17,7 @@ /// ``` library; +import 'dart:async'; import 'dart:convert'; import 'dart:io'; @@ -217,7 +218,12 @@ bool _sameConstraint(String? local, Object? published) { } } -Future _httpGet(Uri uri) async { +/// Fetches [uri], failing when the connection takes over 30 seconds, or the +/// response headers or [bodyTimeout] pass first. +Future pubDevGet( + Uri uri, { + Duration bodyTimeout = const Duration(seconds: 60), +}) async { final client = HttpClient()..connectionTimeout = const Duration(seconds: 30); try { final request = await client.getUrl(uri); @@ -225,50 +231,78 @@ Future _httpGet(Uri uri) async { final body = await response .transform(utf8.decoder) .join() - .timeout(const Duration(seconds: 60)); + .timeout(bodyTimeout); return (status: response.statusCode, body: body); } finally { client.close(force: true); } } -String _baseName(String path) => - path.split(RegExp(r'[/\\]')).where((part) => part.isNotEmpty).last; - -Future main(List arguments) async { - if (arguments.isNotEmpty) { - stderr.writeln('Usage: dart run tool/release/companion_pub_preflight.dart'); - exitCode = 64; - return; +/// Calls [get] for [uri], and once more after [retryDelay] when it throws an +/// [Exception], such as a stalled body's [TimeoutException], or pub.dev +/// answers a 5xx status. +Future getWithOneRetry( + Uri uri, + Future Function(Uri uri) get, { + Duration retryDelay = const Duration(seconds: 5), +}) async { + try { + final response = await get(uri); + if (response.status < HttpStatus.internalServerError) return response; + } on Exception { + // Retried below; a second failure reaches the caller. } - final companions = discoverAppleCompanionPackages(Directory.current); + await Future.delayed(retryDelay); + return get(uri); +} + +/// Runs both preflight checks on the companions under [repoRoot], fetching +/// pub.dev through [get], reports to [out] or [err], and returns the exit +/// code: `0` only when no problem stops the release. +Future runCompanionPubPreflight( + Directory repoRoot, + Future Function(Uri uri) get, { + required StringSink out, + required StringSink err, +}) async { + final companions = discoverAppleCompanionPackages(repoRoot); if (companions.isEmpty) { - stderr.writeln( - 'No Flutter Apple companion packages found under packages/.', - ); - exitCode = 1; - return; + err.writeln('No Flutter Apple companion packages found under packages/.'); + return 1; } final problems = [ ...await companionPubPreflightProblems( companions, - (uri) async => (await _httpGet(uri)).status, - ), - ...await companionPublishedConstraintProblems( - Directory.current, - companions, - _httpGet, + (uri) async => (await get(uri)).status, ), + ...await companionPublishedConstraintProblems(repoRoot, companions, get), ]; if (problems.isNotEmpty) { - stderr.writeln('Companion pub.dev preflight failed:'); - problems.forEach(stderr.writeln); - exitCode = 1; - return; + err.writeln('Companion pub.dev preflight failed:'); + problems.forEach(err.writeln); + return 1; } - stdout.writeln( + out.writeln( 'Companion packages exist on pub.dev, and no published companion ' 'version declares a different llamadart constraint: ' '${companions.map((companion) => companion.name).join(', ')}.', ); + return 0; +} + +String _baseName(String path) => + path.split(RegExp(r'[/\\]')).where((part) => part.isNotEmpty).last; + +Future main(List arguments) async { + if (arguments.isNotEmpty) { + stderr.writeln('Usage: dart run tool/release/companion_pub_preflight.dart'); + exitCode = 64; + return; + } + exitCode = await runCompanionPubPreflight( + Directory.current, + (uri) => getWithOneRetry(uri, pubDevGet), + out: stdout, + err: stderr, + ); } diff --git a/tool/testing/verify_release_docs_versions.dart b/tool/testing/verify_release_docs_versions.dart index 59141e392..e45b55f8b 100644 --- a/tool/testing/verify_release_docs_versions.dart +++ b/tool/testing/verify_release_docs_versions.dart @@ -386,10 +386,17 @@ List checkCompanionCoreConstraints( min > coreVersion || max != Version(coreVersion.major, coreVersion.minor + 1, 0)) { errors.add( - "${companion.pubspecPath} declares `llamadart: '$constraint'`, but " - 'core is $coreVersion; a companion must allow exactly this core ' - "minor, `'$expected'` for a new minor. Bump the companion version " - 'with it, because pub.dev never changes a published constraint.', + coreVersion.isPreRelease + ? "${companion.pubspecPath} declares `llamadart: '$constraint'`, " + 'but core is the prerelease $coreVersion. Release ' + 'automation publishes only stable core versions; set a ' + 'stable core version, then constrain each companion to its ' + 'minor.' + : "${companion.pubspecPath} declares `llamadart: '$constraint'`, " + 'but core is $coreVersion; a companion must allow exactly ' + "this core minor, `'$expected'` for a new minor. Bump the " + 'companion version with it, because pub.dev never changes a ' + 'published constraint.', ); } } diff --git a/website/docs/maintainers/release-workflow.md b/website/docs/maintainers/release-workflow.md index 65c69c07d..9b14e94a8 100644 --- a/website/docs/maintainers/release-workflow.md +++ b/website/docs/maintainers/release-workflow.md @@ -65,6 +65,10 @@ version alignment: core's; the `0.0.x` companions released beside earlier cores predate the rule. Native pin sync records changed companion native pins under `Unreleased` but does not bump companion package versions by default. +- Release automation publishes only stable core versions and stops before any + tag on a prerelease such as `0.13.0-dev.1`: no companion constraint + `>=M.m.0 /admin` that automated publishing from + GitHub Actions is enabled for `leehack/llamadart` with tag pattern + `-v{{version}}`. The preflight cannot see that setting, and without + it the companion's publish run fails after the core has shipped. + 3. If a changed companion version is missing, keep the PR scoped to release prep and merge it only when the release is approved. The post-merge release workflow pushes the core `vX.Y.Z` tag and waits until the pub.dev package listing, which pub resolves against, includes the new core. 4. The workflow then pushes each missing companion's package-specific tag, waits for `publish_companion_pubdev.yml` to publish it, and re-checks the - pub.dev listing. + pub.dev listing. Pub.dev serves that listing with `max-age=120`, so the + companion publish retries `flutter pub get` twice, a minute apart, when + its first resolution misses the new core. 5. A rerun at the same merge commit finds the core tag already there, skips pushing it, and publishes the companions still missing; a core tag at any - other commit stops the run. A companion whose tag exists but whose version - is not on pub.dev also stops the rerun, because that tag already ran + other commit stops the run. + - If `publish_pubdev.yml` failed after the core tag was pushed, a rerun of + `release_on_prep_merge.yml` alone waits for the core on pub.dev and fails. + Rerun the tag's failed `publish_pubdev.yml` run first, wait for the core + version on pub.dev, then rerun `release_on_prep_merge.yml`. + - A companion tag at another commit whose version is not on pub.dev stops + the run: rerunning its publish would ship that commit's package. Release + it from a new release-prep PR that bumps the core version and the + companion's patch version. + + A companion whose tag exists at the release commit but whose version is + not on pub.dev also stops the rerun, because that tag already ran `publish_companion_pubdev.yml`: - - For a transient failure, such as a pub.dev or runner outage, rerun that - tag's failed `publish_companion_pubdev.yml` run, wait for the version on - pub.dev, then rerun `release_on_prep_merge.yml`. + - For a transient failure, such as a pub.dev or runner outage, or + automated publishing not yet enabled for the package, fix the cause, + rerun that tag's failed `publish_companion_pubdev.yml` run, wait for the + version on pub.dev, then rerun `release_on_prep_merge.yml`. - For a cause in the repository, such as a package that fails `pub publish` validation, the tagged commit cannot publish that version. Fix it in a new release-prep PR that bumps the core version and the @@ -236,7 +259,9 @@ rsync -a --delete \ the GitHub Release exists. Before pushing any tag, `tool/release/companion_pub_preflight.dart` checks that every companion under `packages/` exists on pub.dev and otherwise stops with the - first-publish steps above; publish the package, then rerun the run. + first-publish steps above; publish the package, then rerun the run. It + retries each pub.dev request once after a timeout, including a stalled + body, or a 5xx answer. ## 4. Post-release verification