Skip to content

armgit / macro

Public Imported from GitHub
0

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

perf(sync-service): skip the worker deploy when its inputs are already live (#9709)

teo416e1cd3c4d2
diff --git a/.github/scripts/sync-worker-key.sh b/.github/scripts/sync-worker-key.sh
new file mode 100755
index 0000000000..2cd89fecd2
--- /dev/null
+++ b/.github/scripts/sync-worker-key.sh
@@ -0,0 +1,41 @@
+#!/usr/bin/env bash
+# Prints a key that changes whenever an input to the deployed sync worker changes.
+# Run from the repository root. Keep every input to the worker's bundle covered:
+# a missing input would let the deploy job skip a worker that did change.
+set -euo pipefail
+
+# Hash a finished file, not a pipe: a failure part way through must print no key
+# rather than the hash of partial inputs, which could match a later failure.
+inputs=$(mktemp)
+trap 'rm -f "$inputs"' EXIT
+
+{
+ # The worker's workspace closure, which holds its wrangler config, lockfile,
+ # build script and D1 migrations.
+ jq -r '.closures.sync_service[]' .github/workspace-dep-closures.json |
+ LC_ALL=C sort |
+ while read -r dir; do
+ printf '%s %s\n' "$dir" "$(git rev-parse "HEAD:$dir")"
+ done
+
+ # Third-party crates and features as the worker resolves them, so a Cargo.lock
+ # change that only affects other packages leaves the key alone. Path crates
+ # are dropped here because the closure above already hashes them.
+ cargo tree --locked -p sync_service --target wasm32-unknown-unknown \
+ -e normal,build -f '{p} {f}' --prefix none |
+ sed -E 's/ \(\*\)$//; s# \(/[^)]*\)##' |
+ LC_ALL=C sort -u
+
+ # Build settings that live outside the closure.
+ for path in rust-toolchain.toml .cargo/config.toml vendor; do
+ if git cat-file -e "HEAD:$path" 2>/dev/null; then
+ printf '%s %s\n' "$path" "$(git rev-parse "HEAD:$path")"
+ fi
+ done
+ python3 -I -c 'import tomllib
+manifest = tomllib.load(open("Cargo.toml", "rb"))
+print(sorted(manifest.get("profile", {}).items()))
+print(sorted(manifest.get("patch", {}).items()))'
+} >"$inputs"
+
+sha256sum "$inputs" | cut -d' ' -f1
diff --git a/.github/scripts/sync-worker-state.sh b/.github/scripts/sync-worker-state.sh
new file mode 100755
index 0000000000..738c1bab4a
--- /dev/null
+++ b/.github/scripts/sync-worker-state.sh
@@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+# Compares WORKER_KEY with the version live in ENVIRONMENT and writes `unchanged`
+# and `wait_seconds` to GITHUB_OUTPUT. Run from services/sync-service.
+#
+# The comparison is with what Cloudflare is serving, not the previous push, so a
+# cancelled run or a rollback can't make a change look deployed. Anything it
+# can't read means deploy: the worst case is the slower path, never a skipped
+# worker.
+set -uo pipefail
+
+deferral_seconds=300
+
+deploy() {
+ echo "Deploying the worker: $1"
+ {
+ echo "unchanged=false"
+ echo "wait_seconds=$deferral_seconds"
+ } >>"$GITHUB_OUTPUT"
+ exit 0
+}
+
+[ -n "${WORKER_KEY:-}" ] || deploy "no input key"
+
+status=$(npx wrangler deployments status --env "$ENVIRONMENT" --json) ||
+ deploy "could not read the live deployment"
+# A gradual rollout serves two versions, so a single message can't describe it.
+version=$(jq -er 'select((.versions | length) == 1 and .versions[0].percentage == 100) | .versions[0].version_id' <<<"$status") ||
+ deploy "the live deployment is not one version at 100%"
+created_on=$(jq -er '.created_on' <<<"$status") ||
+ deploy "the live deployment has no creation time"
+created_at=$(date -d "$created_on" +%s) ||
+ deploy "could not parse the live deployment time"
+
+details=$(npx wrangler versions view "$version" --env "$ENVIRONMENT" --json) ||
+ deploy "could not read live version $version"
+message=$(jq -er '.annotations["workers/message"]' <<<"$details") ||
+ deploy "live version $version has no input key"
+[ "$message" = "inputs:$WORKER_KEY" ] ||
+ deploy "live version $version has different inputs"
+
+# The previous deployment may have been cancelled during its wait, so wait out
+# whatever is left of the deferral rather than assuming it finished.
+wait_seconds=$((deferral_seconds - ($(date +%s) - created_at)))
+if [ "$wait_seconds" -lt 0 ]; then wait_seconds=0; fi
+if [ "$wait_seconds" -gt "$deferral_seconds" ]; then wait_seconds=$deferral_seconds; fi
+
+echo "Worker inputs match live version $version; skipping deployment, waiting ${wait_seconds}s."
+{
+ echo "unchanged=true"
+ echo "wait_seconds=$wait_seconds"
+} >>"$GITHUB_OUTPUT"
diff --git a/.github/workflows/deploy_on_push.yml b/.github/workflows/deploy_on_push.yml
index 596ef07785..7a7b0fee4a 100644
--- a/.github/workflows/deploy_on_push.yml
+++ b/.github/workflows/deploy_on_push.yml
@@ -17,8 +17,9 @@
# Deploying everything unconditionally makes the coalescing lossless: the
# surviving run always deploys a superset of the runs it displaced. The
# called workflows already avoid redundant work internally (Nix-cached
-# builds, Pulumi no-ops on unchanged stacks), so the cost is small next to
-# an undeployed commit.
+# builds, Pulumi no-ops on unchanged stacks, the sync worker comparing its
+# inputs with the live version), so the cost is small next to an undeployed
+# commit. Those checks compare with what is deployed, never the last push.
#
name: Deploy on Push
on:
diff --git a/.github/workflows/deploy_sync_service.yml b/.github/workflows/deploy_sync_service.yml
index c4b5d1f7f2..442a64c14f 100644
--- a/.github/workflows/deploy_sync_service.yml
+++ b/.github/workflows/deploy_sync_service.yml
@@ -60,7 +60,21 @@ jobs:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
working-directory: services/sync-service
+ - id: worker-key
+ name: Compute worker input key
+ run: echo "key=$(.github/scripts/sync-worker-key.sh)" >> "$GITHUB_OUTPUT"
+ continue-on-error: true
+ - id: worker-state
+ name: Compare with the live worker
+ run: ../../.github/scripts/sync-worker-state.sh
+ env:
+ ENVIRONMENT: ${{ inputs.environment || 'dev' }}
+ WORKER_KEY: ${{ steps.worker-key.outputs.key }}
+ CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
+ CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
+ working-directory: services/sync-service
- name: Apply D1 migrations
+ if: ${{ steps.worker-state.outputs.unchanged != 'true' }}
run: npx wrangler d1 migrations apply USER_PEER_MAPPING --env ${{ inputs.environment || 'dev' }} --remote
env:
CI: 'true'
@@ -68,12 +82,16 @@ jobs:
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
working-directory: services/sync-service
- name: Deploy with wrangler
- run: npx wrangler deploy --env ${{ inputs.environment || 'dev' }}
+ if: ${{ steps.worker-state.outputs.unchanged != 'true' }}
+ run: npx wrangler deploy --env ${{ inputs.environment || 'dev' }} --message "inputs:$WORKER_KEY"
env:
+ WORKER_KEY: ${{ steps.worker-key.outputs.key }}
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
working-directory: services/sync-service
- name: Wait for active Durable Objects to update
- run: sleep 300
+ run: sleep "$WAIT_SECONDS"
+ env:
+ WAIT_SECONDS: ${{ steps.worker-state.outputs.wait_seconds }}
concurrency:
group: deploy-sync-service-${{ inputs.environment || 'dev' }}
diff --git a/services/sync-service/AGENTS.md b/services/sync-service/AGENTS.md
index c587232c79..75c4a0b440 100644
--- a/services/sync-service/AGENTS.md
+++ b/services/sync-service/AGENTS.md
@@ -92,6 +92,7 @@ to the requested surface. These are scoped sync JWTs, not app-session tokens.
- Deploy `PeerCommentUpdate` support before clients send it; validate these frames as comment-only for editors as well as commenters, and reject viewers.
- Never run `just deploy-dev` / `just deploy-prod` without explicit approval.
- Wait at least five minutes after a manual worker deployment before publishing clients that require its new protocol; the CI worker job waits out Durable Objects' default 300-second code-update deferral.
+- A new input to the worker's bundle that lives outside its workspace closure must be added to `.github/scripts/sync-worker-key.sh`, or CI can skip deploying a changed worker.
## Related
diff --git a/services/sync-service/README.md b/services/sync-service/README.md
index 0baead7edf..fd2f6be601 100644
--- a/services/sync-service/README.md
+++ b/services/sync-service/README.md
@@ -54,6 +54,9 @@ for this message before deploying clients that send it; the dev push and
production release workflows enforce this order while building the web app in
parallel. The worker deployment job waits 300 seconds after deployment for
[active Durable Objects to adopt the new code](https://developers.cloudflare.com/durable-objects/deployments/durable-objects-code-updates/).
+When the live version was built from the same inputs, recorded in its deployment
+message, the job skips migrations and deployment and waits only for what remains
+of those 300 seconds.
Manual deployments must preserve the same order and wait at least five minutes
before publishing clients. Keep the workflow wait aligned with any future
`code_update_strategy` change. Older workers refuse
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_on_push.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_on_push.rs
index ded12d8c2f..5dbe47ad53 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_on_push.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_on_push.rs
@@ -15,8 +15,10 @@
//! always a superset of the ones it displaced.
//!
//! The called workflows already avoid redundant work internally (the service
-//! matrix is Nix-cached and Pulumi no-ops unchanged stacks), so the cost of
-//! dropping the gate is small next to a silently undeployed commit.
+//! matrix is Nix-cached, Pulumi no-ops unchanged stacks, and the sync worker
+//! compares its inputs with the live version), so the cost of dropping the gate
+//! is small next to a silently undeployed commit. Those checks are safe because
+//! they compare with what is deployed, not with the previous push.
//!
//! Replaces the separate `deploy_cloud_storage_on_push` and
//! `deploy_web_app_dev_push` workflows. Generated into `deploy_on_push.yml`
@@ -58,8 +60,9 @@ pub const NOTICE: &str = indoc::indoc! {"
# Deploying everything unconditionally makes the coalescing lossless: the
# surviving run always deploys a superset of the runs it displaced. The
# called workflows already avoid redundant work internally (Nix-cached
- # builds, Pulumi no-ops on unchanged stacks), so the cost is small next to
- # an undeployed commit.
+ # builds, Pulumi no-ops on unchanged stacks, the sync worker comparing its
+ # inputs with the live version), so the cost is small next to an undeployed
+ # commit. Those checks compare with what is deployed, never the last push.
#
"};
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_on_push/test.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_on_push/test.rs
index da13575801..e45bcba536 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_on_push/test.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_on_push/test.rs
@@ -51,7 +51,7 @@ fn sync_deployment_waits_for_active_objects_before_unblocking_clients() -> Resul
.expect("worker deployment");
let wait = steps
.iter()
- .position(|step| step["run"].as_str() == Some("sleep 300"))
+ .position(|step| step["run"].as_str() == Some("sleep \"$WAIT_SECONDS\""))
.expect("the worker job must wait out the default code-update deferral");
assert!(deploy < wait);
assert!(steps[wait]["if"].is_null());
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_sync_service.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_sync_service.rs
index 6a99669fce..ec7bc556cb 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_sync_service.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_sync_service.rs
@@ -5,6 +5,11 @@
//! deploys to dev come through [`crate::workflows::deploy_on_push`] (which owns
//! deployment ordering) and prod deploys through `release-production`. Generated
//! into `deploy_sync_service.yml`.
+//!
+//! The job skips migrations, deployment and the wait when the live worker was
+//! built from the same inputs. It compares with the version Cloudflare is
+//! serving, not with the previous push, so runs that were cancelled in the
+//! queue can't make an undeployed change look deployed.
use anyhow::Result;
use gh_workflow::{
@@ -13,6 +18,9 @@ use gh_workflow::{
use crate::workflows::{runners, steps, vars};
+#[cfg(test)]
+mod test;
+
const ENVIRONMENT: &str = "${{ inputs.environment || 'dev' }}";
pub fn deploy_sync_service() -> Workflow {
@@ -78,6 +86,8 @@ fn deploy() -> Job {
.add_step(setup_node())
.add_step(install_deps())
.add_step(check_secrets())
+ .add_step(compute_worker_key())
+ .add_step(read_worker_state())
.add_step(apply_d1_migrations())
.add_step(deploy_step())
.add_step(wait_for_active_objects())
@@ -114,6 +124,27 @@ fn check_secrets() -> Step<Run> {
.add_env(("CLOUDFLARE_ACCOUNT_ID", vars::CLOUDFLARE_ACCOUNT_ID))
}
+const WORKER_CHANGED: &str = "${{ steps.worker-state.outputs.unchanged != 'true' }}";
+
+/// A failure here leaves the key empty, which the next step treats as changed.
+fn compute_worker_key() -> Step<Run> {
+ Step::new("Compute worker input key")
+ .run("echo \"key=$(.github/scripts/sync-worker-key.sh)\" >> \"$GITHUB_OUTPUT\"")
+ .id("worker-key")
+ .continue_on_error(true)
+}
+
+fn read_worker_state() -> Step<Run> {
+ Step::new("Compare with the live worker")
+ .run("../../.github/scripts/sync-worker-state.sh")
+ .id("worker-state")
+ .working_directory(xtask_paths::repo_dir!("services/sync-service"))
+ .add_env(("ENVIRONMENT", ENVIRONMENT))
+ .add_env(("WORKER_KEY", "${{ steps.worker-key.outputs.key }}"))
+ .add_env(("CLOUDFLARE_API_TOKEN", vars::CLOUDFLARE_API_TOKEN))
+ .add_env(("CLOUDFLARE_ACCOUNT_ID", vars::CLOUDFLARE_ACCOUNT_ID))
+}
+
/// Migrate first: new code against an already-migrated D1 is safe, the reverse
/// is a live error.
fn apply_d1_migrations() -> Step<Run> {
@@ -121,6 +152,7 @@ fn apply_d1_migrations() -> Step<Run> {
.run(format!(
"npx wrangler d1 migrations apply USER_PEER_MAPPING --env {ENVIRONMENT} --remote"
))
+ .if_condition(Expression::new(WORKER_CHANGED))
.working_directory(xtask_paths::repo_dir!("services/sync-service"))
.add_env(("CI", "true"))
.add_env(("CLOUDFLARE_API_TOKEN", vars::CLOUDFLARE_API_TOKEN))
@@ -129,8 +161,12 @@ fn apply_d1_migrations() -> Step<Run> {
fn deploy_step() -> Step<Run> {
Step::new("Deploy with wrangler")
- .run(format!("npx wrangler deploy --env {ENVIRONMENT}"))
+ .run(format!(
+ "npx wrangler deploy --env {ENVIRONMENT} --message \"inputs:$WORKER_KEY\""
+ ))
+ .if_condition(Expression::new(WORKER_CHANGED))
.working_directory(xtask_paths::repo_dir!("services/sync-service"))
+ .add_env(("WORKER_KEY", "${{ steps.worker-key.outputs.key }}"))
.add_env(("CLOUDFLARE_API_TOKEN", vars::CLOUDFLARE_API_TOKEN))
.add_env(("CLOUDFLARE_ACCOUNT_ID", vars::CLOUDFLARE_ACCOUNT_ID))
}
@@ -138,6 +174,13 @@ fn deploy_step() -> Step<Run> {
/// Active Durable Objects can defer code adoption for 300 seconds by default.
/// Keep dependent clients behind that window without forcing sessions to reset
/// early. Keep this delay aligned with any future `code_update_strategy` change.
+/// `sync-worker-state.sh` holds the 300 seconds; a skipped deployment waits only
+/// for what remains since the live version was deployed.
fn wait_for_active_objects() -> Step<Run> {
- Step::new("Wait for active Durable Objects to update").run("sleep 300")
+ Step::new("Wait for active Durable Objects to update")
+ .run("sleep \"$WAIT_SECONDS\"")
+ .add_env((
+ "WAIT_SECONDS",
+ "${{ steps.worker-state.outputs.wait_seconds }}",
+ ))
}
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_sync_service/test.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_sync_service/test.rs
new file mode 100644
index 0000000000..f0174468ef
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_sync_service/test.rs
@@ -0,0 +1,242 @@
+use std::os::unix::fs::PermissionsExt;
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+fn scripts_dir() -> PathBuf {
+ xtask_paths::repo_root().join(".github/scripts")
+}
+
+fn write_executable(path: &Path, contents: &str) {
+ std::fs::write(path, contents).unwrap();
+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
+}
+
+fn path_with(dir: &Path) -> String {
+ format!("{}:{}", dir.display(), std::env::var("PATH").unwrap())
+}
+
+/// Runs a script from `.github/scripts` so the fakes on `path` win: CI's Nix dev
+/// shell sets `BASH_ENV`, which would otherwise put the real tools back in front.
+fn script_command(name: &str, dir: &Path, path: &str) -> Command {
+ let mut command = Command::new("bash");
+ command
+ .arg(scripts_dir().join(name))
+ .current_dir(dir)
+ .env("PATH", path)
+ .env_remove("BASH_ENV");
+ command
+}
+
+/// Runs the state script with a fake `npx` and returns (`unchanged`, `wait_seconds`, success).
+fn worker_state(key: &str, status: &str, view: &str) -> (String, i64, bool) {
+ let dir = tempfile::tempdir().unwrap();
+ write_executable(
+ &dir.path().join("npx"),
+ &format!(
+ "#!/usr/bin/env bash\ncase \"$2\" in\n deployments) {status} ;;\n versions) {view} ;;\n *) exit 99 ;;\nesac\n"
+ ),
+ );
+ let output_path = dir.path().join("output");
+ std::fs::write(&output_path, "").unwrap();
+ let output = script_command("sync-worker-state.sh", dir.path(), &path_with(dir.path()))
+ .env("GITHUB_OUTPUT", &output_path)
+ .env("ENVIRONMENT", "dev")
+ .env("WORKER_KEY", key)
+ .output()
+ .unwrap();
+ let written = std::fs::read_to_string(output_path).unwrap();
+ let value = |name: &str| {
+ written
+ .lines()
+ .find_map(|line| line.strip_prefix(&format!("{name}=")).map(str::to_string))
+ .unwrap_or_default()
+ };
+ (
+ value("unchanged"),
+ value("wait_seconds").parse().unwrap_or(-1),
+ output.status.success(),
+ )
+}
+
+fn status_at(seconds_ago: i64) -> String {
+ let created_on = String::from_utf8(
+ Command::new("date")
+ .args(["-u", "-d", &format!("{seconds_ago} seconds ago"), "+%FT%TZ"])
+ .output()
+ .unwrap()
+ .stdout,
+ )
+ .unwrap();
+ format!(
+ "echo '{{\"created_on\":\"{}\",\"versions\":[{{\"version_id\":\"v1\",\"percentage\":100}}]}}'",
+ created_on.trim()
+ )
+}
+
+const MATCHING_VIEW: &str = "echo '{\"annotations\":{\"workers/message\":\"inputs:abc\"}}'";
+
+#[test]
+fn matching_inputs_skip_deployment_once_the_deferral_has_passed() {
+ let (unchanged, wait, ok) = worker_state("abc", &status_at(3600), MATCHING_VIEW);
+ assert!(ok);
+ assert_eq!(unchanged, "true");
+ assert_eq!(wait, 0);
+}
+
+#[test]
+fn matching_inputs_wait_out_what_remains_of_a_recent_deployment() {
+ // A run cancelled during its wait must not unblock clients early.
+ let (unchanged, wait, ok) = worker_state("abc", &status_at(100), MATCHING_VIEW);
+ assert!(ok);
+ assert_eq!(unchanged, "true");
+ assert!((190..=200).contains(&wait), "waited {wait}");
+}
+
+#[test]
+fn anything_but_a_clear_match_deploys_and_waits_in_full() {
+ let two_versions = "echo '{\"created_on\":\"2026-01-01T00:00:00Z\",\"versions\":[{\"version_id\":\"a\",\"percentage\":50},{\"version_id\":\"b\",\"percentage\":50}]}'";
+ let partial = "echo '{\"created_on\":\"2026-01-01T00:00:00Z\",\"versions\":[{\"version_id\":\"a\",\"percentage\":10}]}'";
+ let old = status_at(3600);
+ for (name, key, status, view) in [
+ ("different inputs", "other", old.as_str(), MATCHING_VIEW),
+ ("no key", "", old.as_str(), MATCHING_VIEW),
+ ("status fails", "abc", "exit 1", MATCHING_VIEW),
+ ("status is not JSON", "abc", "echo nope", MATCHING_VIEW),
+ ("no deployment", "abc", "echo null", MATCHING_VIEW),
+ ("gradual rollout", "abc", two_versions, MATCHING_VIEW),
+ ("partial rollout", "abc", partial, MATCHING_VIEW),
+ ("view fails", "abc", old.as_str(), "exit 1"),
+ (
+ "no message",
+ "abc",
+ old.as_str(),
+ "echo '{\"annotations\":{}}'",
+ ),
+ ("no annotations", "abc", old.as_str(), "echo '{}'"),
+ ] {
+ let (unchanged, wait, ok) = worker_state(key, status, view);
+ assert!(ok, "{name}: a read failure must not fail the job");
+ assert_eq!(unchanged, "false", "{name}");
+ assert_eq!(wait, 300, "{name}");
+ }
+}
+
+fn git(dir: &Path, args: &[&str]) {
+ let status = Command::new("git")
+ .args(["-c", "user.name=t", "-c", "[email protected]"])
+ .args(args)
+ .current_dir(dir)
+ .output()
+ .unwrap()
+ .status;
+ assert!(status.success(), "git {args:?}");
+}
+
+fn commit_change(dir: &Path, file: &str, contents: &str) {
+ let path = dir.join(file);
+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
+ std::fs::write(path, contents).unwrap();
+ git(dir, &["add", "-A"]);
+ git(dir, &["commit", "-qm", "change"]);
+}
+
+fn worker_key(dir: &Path) -> String {
+ let output = script_command("sync-worker-key.sh", dir, &path_with(&dir.join("bin")))
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ String::from_utf8(output.stdout).unwrap().trim().to_string()
+}
+
+#[test]
+fn the_key_follows_worker_inputs_and_ignores_everything_else() {
+ let repo = tempfile::tempdir().unwrap();
+ let dir = repo.path();
+ let bin = dir.join("bin");
+ std::fs::create_dir(&bin).unwrap();
+ // The fake resolver reads a tracked file, standing in for what the worker resolves.
+ write_executable(
+ &bin.join("cargo"),
+ "#!/usr/bin/env bash\ncat resolved.txt\n",
+ );
+ git(dir, &["init", "-q"]);
+ for (file, contents) in [
+ (
+ ".github/workspace-dep-closures.json",
+ r#"{"closures":{"sync_service":["services/sync-service"]}}"#,
+ ),
+ ("services/sync-service/src/lib.rs", "one"),
+ ("services/other/src/lib.rs", "one"),
+ ("Cargo.toml", "[profile.release]\nlto = false\n"),
+ ("resolved.txt", "serde v1.0.0 default\n"),
+ ("rust-toolchain.toml", "[toolchain]\nchannel = \"1.94.0\"\n"),
+ ] {
+ commit_change(dir, file, contents);
+ }
+ let base = worker_key(dir);
+
+ commit_change(dir, "services/other/src/lib.rs", "two");
+ commit_change(
+ dir,
+ "Cargo.toml",
+ "[profile.release]\nlto = false\n[workspace.dependencies]\nother = \"1\"\n",
+ );
+ assert_eq!(worker_key(dir), base, "unrelated changes must not count");
+
+ let mut previous = base;
+ for (name, file, contents) in [
+ ("worker source", "services/sync-service/src/lib.rs", "two"),
+ ("resolved crates", "resolved.txt", "serde v1.0.1 default\n"),
+ (
+ "toolchain",
+ "rust-toolchain.toml",
+ "[toolchain]\nchannel = \"1.95.0\"\n",
+ ),
+ ("cargo config", ".cargo/config.toml", "[build]\n"),
+ ("vendored crate", "vendor/patched/src/lib.rs", "one"),
+ (
+ "release profile",
+ "Cargo.toml",
+ "[profile.release]\nlto = true\n[workspace.dependencies]\nother = \"1\"\n",
+ ),
+ ] {
+ commit_change(dir, file, contents);
+ let key = worker_key(dir);
+ assert_ne!(key, previous, "{name} must change the key");
+ previous = key;
+ }
+}
+
+#[test]
+fn a_failed_input_read_prints_no_key() {
+ let repo = tempfile::tempdir().unwrap();
+ let dir = repo.path();
+ let bin = dir.join("bin");
+ std::fs::create_dir(&bin).unwrap();
+ write_executable(
+ &bin.join("cargo"),
+ "#!/usr/bin/env bash\necho partial\nexit 1\n",
+ );
+ git(dir, &["init", "-q"]);
+ commit_change(
+ dir,
+ ".github/workspace-dep-closures.json",
+ r#"{"closures":{"sync_service":["services/sync-service"]}}"#,
+ );
+ commit_change(dir, "services/sync-service/src/lib.rs", "one");
+ commit_change(dir, "Cargo.toml", "");
+
+ let output = script_command("sync-worker-key.sh", dir, &path_with(&bin))
+ .output()
+ .unwrap();
+
+ assert!(!output.status.success());
+ assert!(
+ output.stdout.is_empty(),
+ "a partial hash could later match and skip a deployment"
+ );
+}