Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix: retry transient macOS package timestamp failures
Richie McIlroyb02cf38a8132
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 7bbbc8f00..67e9d76f1 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -32,6 +32,7 @@ jobs:with:filters: |desktop:+ - '.gitattributes'- '.github/actions/install-desktop-deps/**'- '.github/workflows/ci.yml'- 'apps/cli/**'@@ -44,7 +45,8 @@ jobs:- 'packages/web-api-contract/**'- 'scripts/build-desktop-binaries*'- 'scripts/build-gpui-binary.sh'- - 'scripts/prepare-gpui-dependency.sh'+ - 'scripts/build-macos-packages*'+ - 'scripts/prepare-gpui-dependency*'- 'scripts/run-gpui-build*'- 'scripts/sync-desktop-versions.mjs'- 'scripts/verify-gpui-release-inputs.mjs'@@ -233,6 +235,9 @@ jobs:- name: Checkout repositoryuses: actions/checkout@v4+ - name: Test desktop build preparation+ run: node --test scripts/prepare-gpui-dependency.test.mjs scripts/build-macos-packages.test.mjs+- name: Install Linux desktop dependenciesif: ${{ runner.os == 'Linux' }}uses: ./.github/actions/install-desktop-depsdiff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.ymlindex beb54916f..12eb8f78f 100644--- a/.github/workflows/desktop-release.yml+++ b/.github/workflows/desktop-release.yml@@ -218,6 +218,14 @@ jobs:with:ref: ${{ inputs.sha }}+ - name: Test GPUI patch checkout+ if: ${{ hashFiles('scripts/prepare-gpui-dependency.test.mjs') != '' }}+ run: node --test scripts/prepare-gpui-dependency.test.mjs++ - name: Test macOS packaging retries+ if: ${{ hashFiles('scripts/build-macos-packages.test.mjs') != '' }}+ run: node --test scripts/build-macos-packages.test.mjs+# Nightly and promoted builds carry a version that differs from the# committed Cargo.toml; Tauri reads the app version from package.version.- name: Stamp build version@@ -340,7 +348,7 @@ jobs:- name: Build appworking-directory: apps/desktop- run: ${{ runner.os == 'Linux' && 'CARGO_PROFILE_RELEASE_DEBUG=0 node ../../scripts/build-linux-packages.mjs' || 'pnpm build:tauri --target' }} ${{ matrix.settings.target }} --config src-tauri/tauri.prod.conf.json ${{ runner.os == 'Windows' && '--bundles nsis' || runner.os == 'Linux' && '--verbose' || '' }}+ run: ${{ runner.os == 'Linux' && 'CARGO_PROFILE_RELEASE_DEBUG=0 node ../../scripts/build-linux-packages.mjs' || runner.os == 'macOS' && hashFiles('scripts/build-macos-packages.mjs') != '' && 'node ../../scripts/build-macos-packages.mjs' || 'pnpm build:tauri --target' }} ${{ matrix.settings.target }} --config src-tauri/tauri.prod.conf.json ${{ runner.os == 'Windows' && '--bundles nsis' || runner.os == 'Linux' && '--verbose' || '' }}env:# https://github.com/tauri-apps/tauri-action/issues/740CI: falsediff --git a/scripts/build-macos-packages.mjs b/scripts/build-macos-packages.mjsnew file mode 100644index 000000000..4dedceca5--- /dev/null+++ b/scripts/build-macos-packages.mjs@@ -0,0 +1,204 @@+import { spawn } from "node:child_process";+import { constants } from "node:os";+import path from "node:path";+import { setTimeout as wait } from "node:timers/promises";+import { fileURLToPath } from "node:url";+import { stripVTControlCharacters } from "node:util";++const desktopDirectory = fileURLToPath(+ new URL("../apps/desktop/", import.meta.url),+);+const retryDelays = [15_000, 30_000];+const outputTailLimit = 64 * 1024;++export function isTimestampSigningFailure(output) {+ const lines = stripVTControlCharacters(output)+ .split(/\r?\n/)+ .map((line) => line.trim())+ .filter(+ (line) =>+ line &&+ !/^ELIFECYCLE\s+Command failed with exit code \d+\.$/.test(line),+ );+ const signingError =+ /^(?:Error\s+)?failed to bundle project: failed to sign app$/;+ if (!signingError.test(lines.pop() ?? "")) return false;+ while (signingError.test(lines.at(-1) ?? "")) lines.pop();+ return /^\/.+: (?:A timestamp was expected but was not found|The timestamp service is not available)\.$/.test(+ lines.at(-1) ?? "",+ );+}++function validateArguments(target, args, platform) {+ let valid =+ platform === "darwin" &&+ /^(?:aarch64|x86_64)-apple-darwin$/.test(target ?? "");+ for (let index = 0; index < args.length && valid; index++) {+ const argument = args[index];+ if (argument === "--config" || argument === "-c") {+ const value = args[++index];+ valid = Boolean(value) && !value.startsWith("-");+ } else {+ valid =+ /^--config=.+/.test(argument) ||+ argument === "--verbose" ||+ /^-v{1,2}$/.test(argument);+ }+ }+ if (!valid) {+ throw new Error(+ "Run on macOS: node scripts/build-macos-packages.mjs <aarch64|x86_64>-apple-darwin [--config <path>] [--verbose]",+ );+ }+}++export function executeMacosCommand(+ args,+ { env, signal, onOutput, spawnProcess = spawn, killProcess = process.kill },+) {+ signal?.throwIfAborted();+ return new Promise((resolve, reject) => {+ const child = spawnProcess("pnpm", args, {+ cwd: desktopDirectory,+ env,+ detached: true,+ stdio: ["ignore", "pipe", "pipe"],+ });+ let commandError;+ let killTimer;+ const terminate = (name) => {+ if (!child.pid) return;+ try {+ killProcess(-child.pid, name);+ } catch (error) {+ if (error.code !== "ESRCH") {+ commandError ??= error;+ child.kill(name);+ }+ }+ };+ const cancel = () => {+ terminate(signal.reason === "SIGINT" ? "SIGINT" : "SIGTERM");+ killTimer = setTimeout(() => terminate("SIGKILL"), 5_000);+ killTimer.unref();+ };+ for (const stream of ["stdout", "stderr"]) {+ child[stream].setEncoding("utf8");+ child[stream].on("data", (chunk) => onOutput(stream, chunk));+ }+ child.once("error", (error) => {+ commandError = error;+ });+ child.once("exit", (_code, childSignal) => {+ if (childSignal) terminate("SIGKILL");+ });+ child.once("close", (code, childSignal) => {+ signal?.removeEventListener("abort", cancel);+ clearTimeout(killTimer);+ if (signal?.aborted) {+ terminate("SIGKILL");+ reject(signal.reason);+ } else if (commandError) {+ reject(commandError);+ } else {+ resolve({ code, signal: childSignal });+ }+ });+ signal?.addEventListener("abort", cancel, { once: true });+ if (signal?.aborted) cancel();+ });+}++export async function buildMacosPackages(+ target,+ args = [],+ {+ platform = process.platform,+ env = process.env,+ signal,+ execute = executeMacosCommand,+ delay = (milliseconds, abortSignal) =>+ wait(milliseconds, undefined, { signal: abortSignal }),+ onOutput = (stream, chunk) => process[stream].write(chunk),+ } = {},+) {+ validateArguments(target, args, platform);+ const commandArguments = ["--target", target, ...args];+ const environment = { ...env, RUST_TARGET_TRIPLE: target };+ for (let attempt = 0; ; attempt++) {+ signal?.throwIfAborted();+ let outputTail = "";+ const command =+ attempt === 0+ ? ["build:tauri", ...commandArguments]+ : [+ "exec",+ "dotenv",+ "-e",+ "../../.env",+ "--",+ "pnpm",+ "tauri",+ "bundle",+ ...commandArguments,+ ];+ const result = await execute(command, {+ env: environment,+ signal,+ onOutput: (stream, chunk) => {+ outputTail = (outputTail + chunk).slice(-outputTailLimit);+ onOutput(stream, chunk);+ },+ });+ signal?.throwIfAborted();+ if (result.error) throw result.error;+ if (+ !Number.isInteger(result.code) ||+ result.code <= 0 ||+ result.code >= 128 ||+ result.signal ||+ attempt === retryDelays.length ||+ !isTimestampSigningFailure(outputTail)+ ) {+ return result;+ }+ onOutput(+ "stderr",+ `Secure timestamp signing failed; retrying macOS packaging in ${retryDelays[attempt] / 1_000}s (${attempt + 1}/${retryDelays.length}).\n`,+ );+ await delay(retryDelays[attempt], signal);+ }+}++async function main() {+ const controller = new AbortController();+ const interrupt = () => controller.abort("SIGINT");+ const terminate = () => controller.abort("SIGTERM");+ process.on("SIGINT", interrupt);+ process.on("SIGTERM", terminate);+ try {+ const [target, ...args] = process.argv.slice(2);+ const result = await buildMacosPackages(target, args, {+ signal: controller.signal,+ });+ process.exitCode = result.signal+ ? 128 + (constants.signals[result.signal] ?? 1)+ : (result.code ?? 1);+ } catch (error) {+ if (!controller.signal.aborted) throw error;+ process.exitCode = 128 + constants.signals[controller.signal.reason];+ } finally {+ process.removeListener("SIGINT", interrupt);+ process.removeListener("SIGTERM", terminate);+ }+}++if (+ process.argv[1] &&+ path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)+) {+ main().catch((error) => {+ console.error(error?.message ?? error);+ process.exitCode = 1;+ });+}diff --git a/scripts/build-macos-packages.test.mjs b/scripts/build-macos-packages.test.mjsnew file mode 100644index 000000000..ad8c44956--- /dev/null+++ b/scripts/build-macos-packages.test.mjs@@ -0,0 +1,364 @@+import assert from "node:assert/strict";+import { EventEmitter } from "node:events";+import { PassThrough } from "node:stream";+import test from "node:test";+import {+ buildMacosPackages,+ executeMacosCommand,+ isTimestampSigningFailure,+} from "./build-macos-packages.mjs";++const target = "x86_64-apple-darwin";+const config = ["--config", "src-tauri/tauri.prod.conf.json"];+const intelTimestampFailure = [+ "/Users/runner/work/Cap/Cap/target/x86_64-apple-darwin/release/bundle/macos/Cap.app/Contents/Frameworks/Spacedrive.framework/Versions/Current/Libraries/libavdevice.61.3.100.dylib: replacing existing signature",+ "/Users/runner/work/Cap/Cap/target/x86_64-apple-darwin/release/bundle/macos/Cap.app/Contents/Frameworks/Spacedrive.framework/Versions/Current/Libraries/libavdevice.61.3.100.dylib: A timestamp was expected but was not found.",+ "failed to bundle project: failed to sign app",+ " Error failed to bundle project: failed to sign app",+ " ELIFECYCLE Command failed with exit code 1.",+ " ELIFECYCLE Command failed with exit code 1.",+ "",+].join("\n");+const armTimestampFailure = [+ "/Users/runner/work/Cap/Cap/target/aarch64-apple-darwin/release/bundle/macos/Cap.app: The timestamp service is not available.",+ " Error failed to bundle project: failed to sign app",+ "",+].join("\n");++function harness(results) {+ const calls = [];+ const delays = [];+ const output = [];+ return {+ calls,+ delays,+ output,+ options: {+ platform: "darwin",+ env: {+ APPLE_SIGNING_IDENTITY: "fixture-identity",+ APPLE_API_KEY_PATH: "fixture-api-key-path",+ TAURI_SIGNING_PRIVATE_KEY: "fixture-updater-key",+ RUST_TARGET_TRIPLE: "previous-target",+ },+ execute: async (args, options) => {+ const result = results[calls.length];+ calls.push({ args, env: options.env });+ assert.ok(result, "Unexpected additional command");+ for (const chunk of result.chunks ?? [result.output ?? ""]) {+ options.onOutput("stderr", chunk);+ }+ return { code: result.code, signal: result.signal ?? null };+ },+ delay: async (milliseconds) => {+ delays.push(milliseconds);+ },+ onOutput: (stream, chunk) => output.push({ stream, chunk }),+ },+ };+}++test("recognizes the observed Intel and ARM signing failures with pnpm and ANSI output", () => {+ assert.equal(isTimestampSigningFailure(intelTimestampFailure), true);+ assert.equal(isTimestampSigningFailure(armTimestampFailure), true);+ assert.equal(+ isTimestampSigningFailure(+ intelTimestampFailure+ .replace(" Error", "\u001b[31m Error\u001b[0m")+ .replaceAll("\n", "\r\n"),+ ),+ true,+ );+});++test("only retries exact timestamp diagnostics with a terminal Tauri signing error", () => {+ for (const output of [+ "Error failed to bundle project: failed to sign app\n",+ intelTimestampFailure.replace(+ "A timestamp was expected but was not found.",+ "The specified item could not be found in the keychain.",+ ),+ intelTimestampFailure.replaceAll(+ "failed to sign app",+ "failed to notarize app",+ ),+ intelTimestampFailure.replace(+ "A timestamp was expected but was not found.",+ "A timestamp was expected but was not found. More details",+ ),+ intelTimestampFailure.replace(+ "failed to bundle project: failed to sign app\n",+ "/Users/runner/work/Cap/Cap/target/x86_64-apple-darwin/release/bundle/macos/Cap.app: The specified item could not be found in the keychain.\nfailed to bundle project: failed to sign app\n",+ ),+ `${intelTimestampFailure}error: could not compile cap-desktop\n`,+ "warning: A timestamp was expected but was not found.\nError failed to bundle project: failed to sign app\n",+ ]) {+ assert.equal(isTimestampSigningFailure(output), false, output);+ }+});++test("successful builds never retry even if their output contains a timestamp diagnostic", async () => {+ const fixture = harness([{ code: 0, output: intelTimestampFailure }]);+ assert.equal(+ (await buildMacosPackages(target, config, fixture.options)).code,+ 0,+ );+ assert.equal(fixture.calls.length, 1);+ assert.deepEqual(fixture.delays, []);+});++test("timestamp retries only rebundle and preserve the target, config and signing environment", async () => {+ const fixture = harness([+ { code: 1, output: intelTimestampFailure },+ { code: 1, output: armTimestampFailure },+ { code: 0 },+ ]);+ const args = [...config, "--config", "extra config.json", "--verbose"];+ const result = await buildMacosPackages(target, args, fixture.options);+ assert.equal(result.code, 0);+ const bundleArguments = [+ "exec",+ "dotenv",+ "-e",+ "../../.env",+ "--",+ "pnpm",+ "tauri",+ "bundle",+ "--target",+ target,+ ...args,+ ];+ assert.deepEqual(+ fixture.calls.map((call) => call.args),+ [+ ["build:tauri", "--target", target, ...args],+ bundleArguments,+ bundleArguments,+ ],+ );+ for (const call of fixture.calls) {+ assert.deepEqual(call.env, {+ ...fixture.options.env,+ RUST_TARGET_TRIPLE: target,+ });+ }+ assert.deepEqual(fixture.delays, [15_000, 30_000]);+});++test("the third timestamp failure stays failed without another attempt", async () => {+ const fixture = harness([+ { code: 1, output: intelTimestampFailure },+ { code: 1, output: armTimestampFailure },+ { code: 65, output: intelTimestampFailure },+ ]);+ assert.equal(+ (await buildMacosPackages(target, config, fixture.options)).code,+ 65,+ );+ assert.equal(fixture.calls.length, 3);+ assert.deepEqual(fixture.delays, [15_000, 30_000]);+});++test("a retry cannot reuse the previous attempt's timestamp diagnostic", async () => {+ const fixture = harness([+ { code: 1, output: intelTimestampFailure },+ { code: 1, output: "Error failed to bundle project: failed to sign app\n" },+ ]);+ assert.equal(+ (await buildMacosPackages(target, config, fixture.options)).code,+ 1,+ );+ assert.equal(fixture.calls.length, 2);+ assert.deepEqual(fixture.delays, [15_000]);+});++test("compiler, certificate, notarization and signal failures are terminal", async () => {+ for (const result of [+ { code: 1, output: "error: could not compile cap-desktop\n" },+ {+ code: 1,+ output:+ "No signing identity found\nError failed to bundle project: failed to sign app\n",+ },+ {+ code: 1,+ output: intelTimestampFailure.replaceAll(+ "failed to sign app",+ "failed to notarize app",+ ),+ },+ { code: 1, signal: "SIGTERM", output: intelTimestampFailure },+ { code: null, signal: "SIGKILL", output: intelTimestampFailure },+ { code: 130, output: intelTimestampFailure },+ { code: 137, output: intelTimestampFailure },+ { code: 143, output: intelTimestampFailure },+ { code: null, output: intelTimestampFailure },+ ]) {+ const fixture = harness([result]);+ assert.deepEqual(+ await buildMacosPackages(target, config, fixture.options),+ { code: result.code, signal: result.signal ?? null },+ );+ assert.equal(fixture.calls.length, 1);+ assert.deepEqual(fixture.delays, []);+ }+});++test("launch failures propagate without retry", async () => {+ const fixture = harness([]);+ const error = new Error("spawn pnpm ENOENT");+ await assert.rejects(+ buildMacosPackages(target, config, {+ ...fixture.options,+ execute: async () => {+ throw error;+ },+ }),+ error,+ );+ assert.deepEqual(fixture.delays, []);+});++test("streams full output while discarding diagnostics outside the bounded tail", async () => {+ const prefix = "build output\n".repeat(8_000);+ const fixture = harness([+ {+ code: 1,+ chunks: [+ intelTimestampFailure,+ prefix,+ "Error failed to bundle project: failed to sign app\n",+ ],+ },+ ]);+ await buildMacosPackages(target, config, fixture.options);+ assert.equal(fixture.calls.length, 1);+ assert.equal(fixture.output[1].chunk, prefix);+ assert.deepEqual(fixture.delays, []);++ const recent = harness([+ { code: 1, chunks: [prefix, intelTimestampFailure] },+ { code: 0 },+ ]);+ await buildMacosPackages(target, config, recent.options);+ assert.equal(recent.calls.length, 2);+});++test("cancellation before execution starts no child", async () => {+ const controller = new AbortController();+ const reason = new Error("cancelled");+ controller.abort(reason);+ const fixture = harness([]);+ await assert.rejects(+ buildMacosPackages(target, config, {+ ...fixture.options,+ signal: controller.signal,+ }),+ reason,+ );+ assert.equal(fixture.calls.length, 0);+});++test("cancellation during execution waits for settlement and never retries", async () => {+ const controller = new AbortController();+ const reason = new Error("cancelled");+ const fixture = harness([]);+ let finish;+ let settled = false;+ const operation = buildMacosPackages(target, config, {+ ...fixture.options,+ signal: controller.signal,+ execute: (_args, options) => {+ options.onOutput("stderr", intelTimestampFailure);+ return new Promise((resolve) => {+ finish = resolve;+ });+ },+ });+ const rejection = assert.rejects(operation, reason).then(() => {+ settled = true;+ });+ controller.abort(reason);+ await Promise.resolve();+ assert.equal(settled, false);+ finish({ code: 1, signal: null });+ await rejection;+ assert.deepEqual(fixture.delays, []);+});++test("cancellation during a retry delay prevents the next command", async () => {+ const controller = new AbortController();+ const reason = new Error("cancelled");+ const fixture = harness([{ code: 1, output: intelTimestampFailure }]);+ await assert.rejects(+ buildMacosPackages(target, config, {+ ...fixture.options,+ signal: controller.signal,+ delay: async () => controller.abort(reason),+ }),+ reason,+ );+ assert.equal(fixture.calls.length, 1);+});++test("the executor cancels the child process group and waits for close", async () => {+ const controller = new AbortController();+ const reason = new Error("cancelled");+ const child = new EventEmitter();+ child.pid = 123;+ child.stdout = new PassThrough();+ child.stderr = new PassThrough();+ const kills = [];+ const output = [];+ let settled = false;+ const operation = executeMacosCommand(["build:tauri"], {+ env: {},+ signal: controller.signal,+ onOutput: (stream, chunk) => output.push({ stream, chunk }),+ spawnProcess: (command, _args, options) => {+ assert.equal(command, "pnpm");+ assert.equal(options.detached, true);+ return child;+ },+ killProcess: (pid, signal) => kills.push({ pid, signal }),+ });+ const rejection = assert.rejects(operation, reason).then(() => {+ settled = true;+ });+ child.stdout.write("building\n");+ child.stderr.write("signing\n");+ controller.abort(reason);+ await Promise.resolve();+ assert.equal(settled, false);+ assert.deepEqual(kills, [{ pid: -123, signal: "SIGTERM" }]);+ child.emit("close", null, "SIGTERM");+ await rejection;+ assert.deepEqual(kills, [+ { pid: -123, signal: "SIGTERM" },+ { pid: -123, signal: "SIGKILL" },+ ]);+ assert.deepEqual(output, [+ { stream: "stdout", chunk: "building\n" },+ { stream: "stderr", chunk: "signing\n" },+ ]);+});++test("unsupported platforms and arguments fail before executing pnpm", async () => {+ for (const [platform, buildTarget, args] of [+ ["win32", target, config],+ ["linux", target, config],+ ["darwin", "x86_64-pc-windows-msvc", config],+ ["darwin", target, ["--config"]],+ ["darwin", target, ["--target", "aarch64-apple-darwin"]],+ ["darwin", target, ["--skip-stapling"]],+ ["darwin", target, ["--no-bundle"]],+ ]) {+ const fixture = harness([]);+ await assert.rejects(+ buildMacosPackages(buildTarget, args, { ...fixture.options, platform }),+ /Run on macOS/,+ );+ assert.equal(fixture.calls.length, 0);+ }+});