Plan: Ephemeral Port Allocation

Status

Step Description Status

1

Add PORT_MAPPINGS constant, port_env_var(), reserve_ports(), discover_port(), discover_all_ports() to xtask/src/docker.rs

Done (2026-04-14) — landed prior to plan-lifecycle bookkeeping; verified 2026-04-26

2

Add export_port_env_vars(), write_ports_env(), load_and_export_ports_env(), mark_ports_status(), print_url_table() to xtask/src/docker.rs

Done (2026-04-14) — landed prior to plan-lifecycle bookkeeping; verified 2026-04-26

3

Wire ephemeral port lifecycle into xtask/src/cmd/dev.rs (start, reload, restart, status)

Done (2026-04-14) — landed prior to plan-lifecycle bookkeeping; verified 2026-04-26

4

Update docker-compose.yml port mappings to use ${CANOPY_PORT_*:-default} env var interpolation

Done (2026-04-14) — landed prior to plan-lifecycle bookkeeping; verified 2026-04-26

5

Fix TANF/Medicaid URL bug in canopy-web clients and docker-compose.yml (8005/8006 to 8014/8015)

Done (2026-04-14) — landed prior to plan-lifecycle bookkeeping; verified 2026-04-26

6

Wire load_and_export_ports_env() into test.rs and e2e.rs so integration tests discover the correct ports

Done (2026-04-14) — landed prior to plan-lifecycle bookkeeping; verified 2026-04-26

7

Add .ports.env to .gitignore

Done (2026-04-14) — landed prior to plan-lifecycle bookkeeping; verified 2026-04-26

8

Unit tests for port_env_var() naming and reserve_ports() uniqueness

Done (2026-04-14) — landed prior to plan-lifecycle bookkeeping; verified 2026-04-26

9

Update documentation (local-dev.md, CLAUDE.md, CHANGELOG.adoc)

Done (2026-04-14) — landed prior to plan-lifecycle bookkeeping; verified 2026-04-26

Branch: feature/ephemeral-ports

Context

Today, docker-compose.yml hardcodes every host port ("8001:8001", "5432:5432", etc.). This means only one canopy devstack can run on a machine at a time — starting a second checkout fails with port conflicts. It also creates friction for developers who happen to have any of the 26 published ports already in use (another Postgres, a local Keycloak, etc.).

The existing check_port_conflicts() function in xtask/src/docker.rs detects conflicts but cannot resolve them. It explicitly tells the developer "Do NOT pick an alternative port — resolve the conflict first." This is the correct behavior when we have no port indirection, but it makes multi-workspace development impossible.

The solution is ephemeral port allocation: before docker compose up, xtask binds TcpListener on 127.0.0.1:0 for each service port to get OS-assigned free ports, exports them as environment variables, and lets compose YAML interpolate via ${CANOPY_PORT_SERVICE_PORT:-default}. Post-startup, docker compose port discovers the authoritative bound ports to eliminate any TOCTOU race between reservation and bind. A .ports.env file persists the mapping so other terminals and test runs can find the ports.

This pattern is proven in the craig codebase (d:\code\craig\xtask\src\docker.rs) and is adapted here for canopy’s 26-service port matrix.

Additionally, this plan fixes a latent URL bug: canopy-web's internal clients and docker-compose.yml environment variables for TANF and Medicaid use ports 8005 and 8006 (which belong to canopy-verification and canopy-enrollment) instead of the correct 8014 and 8015.

Scope

In scope:

  • PORT_MAPPINGS constant enumerating all 26 service/container-port/default-host-port tuples

  • reserve_ports() — ephemeral port reservation via TcpListener::bind("127.0.0.1:0")

  • discover_port() / discover_all_ports() — post-startup authoritative port discovery via docker compose port

  • export_port_env_vars() — set env vars for child docker compose processes, including derived vars (KC_HOSTNAME, KEYCLOAK_ISSUER, CANOPY_TEST__*_URL)

  • write_ports_env() / load_and_export_ports_env() — .ports.env file for cross-terminal persistence

  • print_url_table() — developer-friendly URL summary after startup

  • Docker compose YAML env var interpolation (${CANOPY_PORT_*:-default})

  • Fix TANF/Medicaid URL bug (8005/8006 → 8014/8015) in docker-compose.yml and canopy-web/src/clients.rs

  • Wiring into dev start, dev reload, dev restart, dev status, test, e2e

  • Unit tests for naming convention and port uniqueness

Out of scope:

  • Dynamic container-internal ports (containers continue to listen on their fixed internal ports)

  • Changing the port numbering scheme for container ports (8001-8017, 8080, 8090, etc. remain stable)

  • CI/CD pipeline changes (CI does not run local devstack)

  • Observability stack ports (prometheus 9090, grafana 3000 — these are behind the observability profile and rarely conflict)

Design

Port mapping model

Each entry in PORT_MAPPINGS is a (service_name, container_port, default_host_port) tuple. The env var name follows the pattern CANOPY_PORT_{SERVICE}_{CONTAINER_PORT} where SERVICE is the uppercased service name with hyphens replaced by underscores. For example, ("canopy-rules", 8001, 8001) produces CANOPY_PORT_CANOPY_RULES_8001.

The default host port is the fallback used when no env var is set — this preserves backward compatibility for developers who never run cargo xtask dev start (i.e., they run docker compose up manually).

Lifecycle

  1. Reserve — cargo xtask dev start calls reserve_ports() which binds 26 TcpListener instances to 127.0.0.1:0, records the OS-assigned port, and immediately drops the listener.

  2. Export — export_port_env_vars() sets all CANOPY_PORT_* env vars plus derived vars (KC_HOSTNAME, KEYCLOAK_ISSUER, WEB_EXTERNAL_URL, CANOPY_E2E_BASE_URL, CANOPY_TEST__*_URL) so child docker compose processes inherit them.

  3. Start — docker compose up reads ${CANOPY_PORT_*:-default} from the environment, binding host ports to the ephemeral values.

  4. Discover — After health checks pass, discover_all_ports() uses docker compose port <service> <container_port> to get the authoritative bound port for each service. This eliminates TOCTOU race conditions.

  5. Persist — write_ports_env() writes a .ports.env file with all port env vars and derived vars. mark_ports_status("ready") appends a DEVSTACK_STATUS=ready line.

  6. Reload — Other terminals (test runs, manual curls) call load_and_export_ports_env() to read .ports.env and set all vars in the current process.

TANF/Medicaid URL bug

The docker-compose.yml canopy-web service has:

CANOPY_WEB__TANF_URL: "http://canopy-tanf:8005"       # BUG: should be 8014
CANOPY_WEB__MEDICAID_URL: "http://canopy-medicaid:8006" # BUG: should be 8015

And services/canopy-web/src/clients.rs has matching wrong defaults:

&get("CANOPY_WEB__TANF_URL", "http://localhost:8005"),   // BUG: should be 8014
&get("CANOPY_WEB__MEDICAID_URL", "http://localhost:8006"), // BUG: should be 8015

Port 8005 is canopy-verification and port 8006 is canopy-enrollment. The correct ports are 8014 (canopy-tanf) and 8015 (canopy-medicaid) per their CANOPY_TANFPORT and CANOPY_MEDICAIDPORT environment definitions.

Steps

Step 1: PORT_MAPPINGS constant and core reservation functions

Files: xtask/src/docker.rs

Add the PORT_MAPPINGS constant, the port_env_var() helper, reserve_ports(), discover_port(), and discover_all_ports() to xtask/src/docker.rs.

Add use std::collections::HashMap; and use std::io::Write as IoWrite; to the existing imports.

// ---------------------------------------------------------------------------
// Ephemeral port allocation
// ---------------------------------------------------------------------------

/// All services and their container ports that need host mappings.
/// (service_name, container_port, default_host_port)
pub const PORT_MAPPINGS: &[(&str, u16, u16)] = &[
    ("postgres", 5432, 5432),
    ("rabbitmq", 5672, 5672),
    ("rabbitmq", 15672, 15672),
    ("keycloak", 8080, 8180),
    ("garage", 3900, 3900),
    ("garage", 3903, 3903),
    ("redis", 6379, 6379),
    ("postgres-snap", 5432, 5433),
    ("postgres-tanf", 5432, 5434),
    ("postgres-medicaid", 5432, 5435),
    ("postgres-caps", 5432, 5436),
    ("postgres-wic", 5432, 5437),
    ("canopy-rules", 8001, 8001),
    ("canopy-persons", 8002, 8002),
    ("canopy-applications", 8003, 8003),
    ("canopy-eligibility", 8004, 8004),
    ("canopy-verification", 8005, 8005),
    ("canopy-enrollment", 8006, 8006),
    ("canopy-renewals", 8007, 8007),
    ("canopy-notices", 8008, 8008),
    ("canopy-exchange", 8009, 8009),
    ("canopy-appeals", 8010, 8010),
    ("canopy-reporting", 8011, 8011),
    ("canopy-security", 8012, 8012),
    ("canopy-snap", 8013, 8013),
    ("canopy-tanf", 8014, 8014),
    ("canopy-medicaid", 8015, 8015),
    ("canopy-caps", 8016, 8016),
    ("canopy-wic", 8017, 8017),
    ("canopy-web", 8080, 8080),
    ("canopy-portal", 8090, 8090),
];

Helper to produce env var names:

/// Env var name for a port mapping: CANOPY_PORT_CANOPY_WEB_8080
fn port_env_var(service: &str, container_port: u16) -> String {
    format!(
        "CANOPY_PORT_{}_{}",
        service.to_uppercase().replace('-', "_"),
        container_port
    )
}

Reserve ephemeral ports:

/// Reserve ephemeral ports by binding TcpListener on 127.0.0.1:0.
pub fn reserve_ports() -> Result<HashMap<(String, u16), u16>> {
    let mut ports = HashMap::new();
    for &(service, container_port, _default) in PORT_MAPPINGS {
        let listener = TcpListener::bind("127.0.0.1:0")
            .with_context(|| format!("failed to reserve port for {service}:{container_port}"))?;
        let host_port = listener.local_addr()?.port();
        drop(listener);
        ports.insert((service.to_string(), container_port), host_port);
    }
    Ok(ports)
}

Post-startup discovery:

/// Discover the host port for a running service via `docker compose port`.
pub fn discover_port(service: &str, container_port: u16) -> Result<u16> {
    let output = compose_output(&["port", service, &container_port.to_string()])?;
    let port_str = output
        .rsplit(':')
        .next()
        .with_context(|| format!("unexpected port output for {service}: {output}"))?;
    port_str
        .parse::<u16>()
        .with_context(|| format!("invalid port number for {service}: {port_str}"))
}

/// Discover actual bound ports from running containers via `docker compose port`.
/// This is authoritative — no reservation race conditions.
pub fn discover_all_ports() -> Result<HashMap<(String, u16), u16>> {
    let mut ports = HashMap::new();
    for &(service, container_port, _default) in PORT_MAPPINGS {
        match discover_port(service, container_port) {
            Ok(host_port) => {
                ports.insert((service.to_string(), container_port), host_port);
            }
            Err(e) => {
                eprintln!("  WARN: Could not discover port for {service}:{container_port}: {e}");
            }
        }
    }
    Ok(ports)
}

A private helper for compose_output is also needed (unless reusing compose_cmd output capture). Add a compose_output function that captures stdout from docker compose:

/// Run a docker compose command and capture stdout.
fn compose_output(args: &[&str]) -> Result<String> {
    let root = workspace_root()?;
    let output = Command::new("docker")
        .arg("compose")
        .args(args)
        .current_dir(&root)
        .output()
        .context("failed to run docker compose")?;
    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

Step 2: Environment export, persistence, and URL table

Files: xtask/src/docker.rs

Add export_port_env_vars(), write_ports_env(), load_and_export_ports_env(), mark_ports_status(), and print_url_table().

/// Export port env vars so child `docker compose` inherits them.
/// # Safety
/// `set_var` is unsafe in Rust 2024 edition (not thread-safe). Xtask is single-threaded.
pub fn export_port_env_vars(ports: &HashMap<(String, u16), u16>) {
    unsafe {
        for ((service, container_port), host_port) in ports {
            std::env::set_var(
                port_env_var(service, *container_port),
                host_port.to_string(),
            );
        }

        let kc_port = ports[&("keycloak".to_string(), 8080u16)];
        let web_port = ports[&("canopy-web".to_string(), 8080u16)];

        std::env::set_var(
            "KC_HOSTNAME",
            format!("http://host.docker.internal:{kc_port}"),
        );
        std::env::set_var(
            "KEYCLOAK_ISSUER",
            format!("http://host.docker.internal:{kc_port}/realms/canopy"),
        );
        std::env::set_var(
            "WEB_EXTERNAL_URL",
            format!("http://host.docker.internal:{web_port}"),
        );
        std::env::set_var(
            "CANOPY_E2E_BASE_URL",
            format!("http://host.docker.internal:{web_port}"),
        );

        // Test config vars (CANOPY_TEST__*_URL) — used by nextest/integration tests
        std::env::set_var(
            "CANOPY_TEST__KEYCLOAK_URL",
            format!("http://localhost:{kc_port}"),
        );
        let rules_port = ports[&("canopy-rules".to_string(), 8001u16)];
        let persons_port = ports[&("canopy-persons".to_string(), 8002u16)];
        let applications_port = ports[&("canopy-applications".to_string(), 8003u16)];
        let eligibility_port = ports[&("canopy-eligibility".to_string(), 8004u16)];
        let verification_port = ports[&("canopy-verification".to_string(), 8005u16)];
        let enrollment_port = ports[&("canopy-enrollment".to_string(), 8006u16)];
        let renewals_port = ports[&("canopy-renewals".to_string(), 8007u16)];
        let notices_port = ports[&("canopy-notices".to_string(), 8008u16)];
        let exchange_port = ports[&("canopy-exchange".to_string(), 8009u16)];
        let appeals_port = ports[&("canopy-appeals".to_string(), 8010u16)];
        let reporting_port = ports[&("canopy-reporting".to_string(), 8011u16)];
        let security_port = ports[&("canopy-security".to_string(), 8012u16)];
        let snap_port = ports[&("canopy-snap".to_string(), 8013u16)];
        let tanf_port = ports[&("canopy-tanf".to_string(), 8014u16)];
        let medicaid_port = ports[&("canopy-medicaid".to_string(), 8015u16)];
        let caps_port = ports[&("canopy-caps".to_string(), 8016u16)];
        let wic_port = ports[&("canopy-wic".to_string(), 8017u16)];

        std::env::set_var("CANOPY_TEST__RULES_URL", format!("http://localhost:{rules_port}"));
        std::env::set_var("CANOPY_TEST__PERSONS_URL", format!("http://localhost:{persons_port}"));
        std::env::set_var("CANOPY_TEST__APPLICATIONS_URL", format!("http://localhost:{applications_port}"));
        std::env::set_var("CANOPY_TEST__ELIGIBILITY_URL", format!("http://localhost:{eligibility_port}"));
        std::env::set_var("CANOPY_TEST__VERIFICATION_URL", format!("http://localhost:{verification_port}"));
        std::env::set_var("CANOPY_TEST__ENROLLMENT_URL", format!("http://localhost:{enrollment_port}"));
        std::env::set_var("CANOPY_TEST__RENEWALS_URL", format!("http://localhost:{renewals_port}"));
        std::env::set_var("CANOPY_TEST__NOTICES_URL", format!("http://localhost:{notices_port}"));
        std::env::set_var("CANOPY_TEST__EXCHANGE_URL", format!("http://localhost:{exchange_port}"));
        std::env::set_var("CANOPY_TEST__APPEALS_URL", format!("http://localhost:{appeals_port}"));
        std::env::set_var("CANOPY_TEST__REPORTING_URL", format!("http://localhost:{reporting_port}"));
        std::env::set_var("CANOPY_TEST__SECURITY_URL", format!("http://localhost:{security_port}"));
        std::env::set_var("CANOPY_TEST__SNAP_URL", format!("http://localhost:{snap_port}"));
        std::env::set_var("CANOPY_TEST__TANF_URL", format!("http://localhost:{tanf_port}"));
        std::env::set_var("CANOPY_TEST__MEDICAID_URL", format!("http://localhost:{medicaid_port}"));
        std::env::set_var("CANOPY_TEST__CAPS_URL", format!("http://localhost:{caps_port}"));
        std::env::set_var("CANOPY_TEST__WIC_URL", format!("http://localhost:{wic_port}"));
        std::env::set_var("CANOPY_TEST__WEB_URL", format!("http://localhost:{web_port}"));

        let rabbitmq_port = ports[&("rabbitmq".to_string(), 5672u16)];
        std::env::set_var(
            "CANOPY_TEST__RABBITMQ_URL",
            format!("amqp://canopy:canopy@localhost:{rabbitmq_port}/%2f"),
        );
    }
}

Persist to .ports.env:

/// Write .ports.env file for cross-terminal persistence.
pub fn write_ports_env(ports: &HashMap<(String, u16), u16>) -> Result<()> {
    let root = workspace_root()?;
    let path = root.join(".ports.env");
    let mut file = fs::File::create(&path)?;
    writeln!(
        file,
        "# Auto-generated by cargo xtask dev start — do not edit"
    )?;
    let mut entries: Vec<_> = ports.iter().collect();
    entries.sort_by_key(|((s, p), _)| (s.clone(), *p));
    for ((service, container_port), host_port) in &entries {
        writeln!(
            file,
            "{}={host_port}",
            port_env_var(service, *container_port)
        )?;
    }

    // Derived vars
    let kc_port = ports[&("keycloak".to_string(), 8080u16)];
    let web_port = ports[&("canopy-web".to_string(), 8080u16)];
    writeln!(file, "KC_HOSTNAME=http://host.docker.internal:{kc_port}")?;
    writeln!(file, "KEYCLOAK_ISSUER=http://host.docker.internal:{kc_port}/realms/canopy")?;
    writeln!(file, "WEB_EXTERNAL_URL=http://host.docker.internal:{web_port}")?;
    writeln!(file, "CANOPY_E2E_BASE_URL=http://host.docker.internal:{web_port}")?;

    // Test config vars
    writeln!(file, "CANOPY_TEST__KEYCLOAK_URL=http://localhost:{kc_port}")?;
    for &(service, container_port, _) in PORT_MAPPINGS {
        if service.starts_with("canopy-") && service != "canopy-e2e" && service != "canopy-portal" {
            let short = service.strip_prefix("canopy-").unwrap().to_uppercase().replace('-', "_");
            let hp = ports[&(service.to_string(), container_port)];
            writeln!(file, "CANOPY_TEST__{short}_URL=http://localhost:{hp}")?;
        }
    }
    let web_hp = ports[&("canopy-web".to_string(), 8080u16)];
    writeln!(file, "CANOPY_TEST__WEB_URL=http://localhost:{web_hp}")?;
    let rabbitmq_port = ports[&("rabbitmq".to_string(), 5672u16)];
    writeln!(file, "CANOPY_TEST__RABBITMQ_URL=amqp://canopy:canopy@localhost:{rabbitmq_port}/%2f")?;

    Ok(())
}

Load from .ports.env:

/// Load .ports.env and export all vars to the current process.
/// # Safety
/// `set_var` is unsafe in Rust 2024 edition. Xtask is single-threaded.
pub fn load_and_export_ports_env() -> Result<()> {
    let root = workspace_root()?;
    let path = root.join(".ports.env");
    if path.exists() {
        let content = fs::read_to_string(&path)?;
        for line in content.lines() {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }
            if let Some((key, value)) = line.split_once('=') {
                unsafe { std::env::set_var(key.trim(), value.trim()) };
            }
        }
    }
    Ok(())
}

Status marker:

/// Append a status line to .ports.env indicating devstack readiness.
pub fn mark_ports_status(status: &str) -> Result<()> {
    let root = workspace_root()?;
    let path = root.join(".ports.env");
    let mut file = fs::OpenOptions::new().append(true).open(&path)?;
    writeln!(file, "DEVSTACK_STATUS={status}")?;
    Ok(())
}

URL table for developer convenience:

/// Print a URL table for developer convenience.
pub fn print_url_table(ports: &HashMap<(String, u16), u16>) {
    println!();
    println!("  Service                  URL");
    println!("  ─────────────────────────────────────────");
    let display = [
        ("canopy-web", 8080u16, "http"),
        ("canopy-portal", 8090, "http"),
        ("keycloak", 8080, "http"),
        ("postgres", 5432, "tcp"),
        ("rabbitmq", 15672, "http"),
        ("redis", 6379, "tcp"),
        ("garage", 3900, "http"),
    ];
    for (svc, cp, proto) in display {
        if let Some(&hp) = ports.get(&(svc.to_string(), cp)) {
            if proto == "tcp" {
                println!("  {svc:25} localhost:{hp}");
            } else {
                println!("  {svc:25} {proto}://localhost:{hp}");
            }
        }
    }
    println!();
}

Also add a public helper for looking up host ports from env or discovery:

/// Get the host port for a service from env var or discovery.
pub fn get_host_port(service: &str, container_port: u16) -> Result<u16> {
    let var_name = port_env_var(service, container_port);
    if let Ok(val) = std::env::var(&var_name)
        && let Ok(port) = val.parse::<u16>()
    {
        return Ok(port);
    }
    discover_port(service, container_port)
}

Step 3: Wire into dev.rs lifecycle

Files: xtask/src/cmd/dev.rs

Modify do_start() to call the ephemeral port lifecycle. Remove the call to check_port_conflicts() from Action::Start — ephemeral allocation replaces conflict detection.

In do_start(), before the docker compose up call:

fn do_start(project: &str, shared_db: bool, no_cache: bool, profile: &str) -> Result<()> {
    let mode = if shared_db { " (shared-db)" } else { "" };
    println!("Starting {project} development environment{mode} with profile '{profile}'...");

    // 1. Reserve ephemeral ports
    println!("Reserving ephemeral ports...");
    let reserved = docker::reserve_ports()?;
    docker::export_port_env_vars(&reserved);

    if no_cache {
        docker::compose_cmd(project, &["build", "--no-cache"])?;
    }

    // 2. Start containers (docker compose inherits CANOPY_PORT_* env vars)
    // ... existing up -d logic unchanged ...

    docker::wait_for_health(project)?;

    // 3. Discover authoritative ports and persist
    println!("Discovering bound ports...");
    let discovered = docker::discover_all_ports()?;
    docker::export_port_env_vars(&discovered);
    docker::write_ports_env(&discovered)?;
    docker::mark_ports_status("ready")?;
    docker::print_url_table(&discovered);

    println!("{project} is running. Use `cargo xtask dev status` to check services.");
    Ok(())
}

In Action::Start, remove the docker::check_port_conflicts(&project)?; line.

In Action::Status, after the existing staleness check, add port display:

// Load ports and show URL table
if let Ok(()) = docker::load_and_export_ports_env() {
    if let Ok(ports) = docker::discover_all_ports() {
        docker::print_url_table(&ports);
    }
}

Step 4: Update docker-compose.yml port mappings

Files: docker-compose.yml

Replace every hardcoded "HOST:CONTAINER" port mapping with env var interpolation. The pattern is "${CANOPY_PORT_SERVICE_CONTAINERPORT:-default}:container_port".

Examples of each substitution:

# postgres
ports:
  - "${CANOPY_PORT_POSTGRES_5432:-5432}:5432"

# rabbitmq
ports:
  - "${CANOPY_PORT_RABBITMQ_5672:-5672}:5672"
  - "${CANOPY_PORT_RABBITMQ_15672:-15672}:15672"

# keycloak
ports:
  - "${CANOPY_PORT_KEYCLOAK_8080:-8180}:8080"
# Also update KC_HOSTNAME to use the env var:
environment:
  KC_HOSTNAME: "${KC_HOSTNAME:-http://host.docker.internal:8180}"

# garage
ports:
  - "${CANOPY_PORT_GARAGE_3900:-3900}:3900"
  - "${CANOPY_PORT_GARAGE_3903:-3903}:3903"

# redis
ports:
  - "${CANOPY_PORT_REDIS_6379:-6379}:6379"

# postgres-snap through postgres-wic
ports:
  - "${CANOPY_PORT_POSTGRES_SNAP_5432:-5433}:5432"
  # ... etc for tanf (5434), medicaid (5435), caps (5436), wic (5437)

# canopy-rules through canopy-wic
ports:
  - "${CANOPY_PORT_CANOPY_RULES_8001:-8001}:8001"
  # ... etc for all application services

# canopy-web
ports:
  - "${CANOPY_PORT_CANOPY_WEB_8080:-8080}:8080"

# canopy-portal
ports:
  - "${CANOPY_PORT_CANOPY_PORTAL_8090:-8090}:8090"

Also update KEYCLOAK_ISSUER references in every service’s environment block to use the derived env var:

# For every service that references keycloak:
CANOPY_RULES__KEYCLOAK_ISSUER: "${KEYCLOAK_ISSUER:-http://host.docker.internal:8180/realms/canopy}"

And update canopy-web redirect URL:

CANOPY_WEB__REDIRECT_URL: "${WEB_EXTERNAL_URL:-http://host.docker.internal:8080}/auth/callback"

And the canopy-e2e base URL:

CANOPY_E2E_BASE_URL: ${CANOPY_E2E_BASE_URL:-http://host.docker.internal:8080}

Full list of port mapping substitutions (31 entries):

Service Old New

postgres

"5432:5432"

"${CANOPY_PORT_POSTGRES_5432:-5432}:5432"

rabbitmq (amqp)

"5672:5672"

"${CANOPY_PORT_RABBITMQ_5672:-5672}:5672"

rabbitmq (mgmt)

"15672:15672"

"${CANOPY_PORT_RABBITMQ_15672:-15672}:15672"

keycloak

"8180:8080"

"${CANOPY_PORT_KEYCLOAK_8080:-8180}:8080"

garage (api)

"3900:3900"

"${CANOPY_PORT_GARAGE_3900:-3900}:3900"

garage (web)

"3903:3903"

"${CANOPY_PORT_GARAGE_3903:-3903}:3903"

redis

"6379:6379"

"${CANOPY_PORT_REDIS_6379:-6379}:6379"

postgres-snap

"5433:5432"

"${CANOPY_PORT_POSTGRES_SNAP_5432:-5433}:5432"

postgres-tanf

"5434:5432"

"${CANOPY_PORT_POSTGRES_TANF_5432:-5434}:5432"

postgres-medicaid

"5435:5432"

"${CANOPY_PORT_POSTGRES_MEDICAID_5432:-5435}:5432"

postgres-caps

"5436:5432"

"${CANOPY_PORT_POSTGRES_CAPS_5432:-5436}:5432"

postgres-wic

"5437:5432"

"${CANOPY_PORT_POSTGRES_WIC_5432:-5437}:5432"

canopy-rules

"8001:8001"

"${CANOPY_PORT_CANOPY_RULES_8001:-8001}:8001"

canopy-persons

"8002:8002"

"${CANOPY_PORT_CANOPY_PERSONS_8002:-8002}:8002"

canopy-applications

"8003:8003"

"${CANOPY_PORT_CANOPY_APPLICATIONS_8003:-8003}:8003"

canopy-eligibility

"8004:8004"

"${CANOPY_PORT_CANOPY_ELIGIBILITY_8004:-8004}:8004"

canopy-verification

"8005:8005"

"${CANOPY_PORT_CANOPY_VERIFICATION_8005:-8005}:8005"

canopy-enrollment

"8006:8006"

"${CANOPY_PORT_CANOPY_ENROLLMENT_8006:-8006}:8006"

canopy-renewals

"8007:8007"

"${CANOPY_PORT_CANOPY_RENEWALS_8007:-8007}:8007"

canopy-notices

"8008:8008"

"${CANOPY_PORT_CANOPY_NOTICES_8008:-8008}:8008"

canopy-exchange

"8009:8009"

"${CANOPY_PORT_CANOPY_EXCHANGE_8009:-8009}:8009"

canopy-appeals

"8010:8010"

"${CANOPY_PORT_CANOPY_APPEALS_8010:-8010}:8010"

canopy-reporting

"8011:8011"

"${CANOPY_PORT_CANOPY_REPORTING_8011:-8011}:8011"

canopy-security

"8012:8012"

"${CANOPY_PORT_CANOPY_SECURITY_8012:-8012}:8012"

canopy-snap

"8013:8013"

"${CANOPY_PORT_CANOPY_SNAP_8013:-8013}:8013"

canopy-tanf

"8014:8014"

"${CANOPY_PORT_CANOPY_TANF_8014:-8014}:8014"

canopy-medicaid

"8015:8015"

"${CANOPY_PORT_CANOPY_MEDICAID_8015:-8015}:8015"

canopy-caps

"8016:8016"

"${CANOPY_PORT_CANOPY_CAPS_8016:-8016}:8016"

canopy-wic

"8017:8017"

"${CANOPY_PORT_CANOPY_WIC_8017:-8017}:8017"

canopy-web

"8080:8080"

"${CANOPY_PORT_CANOPY_WEB_8080:-8080}:8080"

canopy-portal

"8090:8090"

"${CANOPY_PORT_CANOPY_PORTAL_8090:-8090}:8090"

Step 5: Fix TANF/Medicaid URL bug

Files: docker-compose.yml, services/canopy-web/src/clients.rs

In docker-compose.yml, under the canopy-web service environment:

# Before (bug):
CANOPY_WEB__TANF_URL: "http://canopy-tanf:8005"
CANOPY_WEB__MEDICAID_URL: "http://canopy-medicaid:8006"

# After (fix):
CANOPY_WEB__TANF_URL: "http://canopy-tanf:8014"
CANOPY_WEB__MEDICAID_URL: "http://canopy-medicaid:8015"

In services/canopy-web/src/clients.rs, fix the fallback defaults:

// Before (bug):
&get("CANOPY_WEB__TANF_URL", "http://localhost:8005"),
&get("CANOPY_WEB__MEDICAID_URL", "http://localhost:8006"),

// After (fix):
&get("CANOPY_WEB__TANF_URL", "http://localhost:8014"),
&get("CANOPY_WEB__MEDICAID_URL", "http://localhost:8015"),

Also fix the unit test assertions:

// Before (bug):
assert_eq!(clients.tanf.base_url, "http://localhost:8005");
assert_eq!(clients.medicaid.base_url, "http://localhost:8006");

// After (fix):
assert_eq!(clients.tanf.base_url, "http://localhost:8014");
assert_eq!(clients.medicaid.base_url, "http://localhost:8015");

Step 6: Wire ports into test and E2E commands

Files: xtask/src/cmd/test.rs, xtask/src/cmd/e2e.rs

In test.rs, before running integration tests (inside run() when !args.unit), load ports:

// Load ephemeral port mappings so integration tests connect to the right ports
if let Err(e) = crate::docker::load_and_export_ports_env() {
    eprintln!("WARN: Could not load .ports.env: {e}");
}

In e2e.rs, at the start of run() before the auto-refresh block, load ports:

// Load ephemeral port mappings for E2E base URL and compose vars
if let Err(e) = crate::docker::load_and_export_ports_env() {
    eprintln!("WARN: Could not load .ports.env: {e}");
}

Step 7: Add .ports.env to .gitignore

Files: .gitignore

Add the following line to .gitignore, under the existing "Devstack staleness markers" section:

# Ephemeral port allocation (cargo xtask dev start writes this)
.ports.env

Step 8: Unit tests

Files: xtask/src/docker.rs

Add unit tests to the existing #[cfg(test)] mod tests block (or create it if it does not exist):

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn port_env_var_naming() {
        assert_eq!(port_env_var("canopy-web", 8080), "CANOPY_PORT_CANOPY_WEB_8080");
        assert_eq!(port_env_var("postgres", 5432), "CANOPY_PORT_POSTGRES_5432");
        assert_eq!(
            port_env_var("postgres-snap", 5432),
            "CANOPY_PORT_POSTGRES_SNAP_5432"
        );
        assert_eq!(
            port_env_var("canopy-medicaid", 8015),
            "CANOPY_PORT_CANOPY_MEDICAID_8015"
        );
    }

    #[test]
    fn reserve_ports_returns_unique() {
        let ports = reserve_ports().unwrap();
        let values: Vec<u16> = ports.values().copied().collect();
        let unique: std::collections::HashSet<u16> = values.iter().copied().collect();
        assert_eq!(values.len(), unique.len(), "all ports must be unique");
        assert_eq!(
            values.len(),
            PORT_MAPPINGS.len(),
            "must reserve a port for every mapping"
        );
    }

    #[test]
    fn port_mappings_has_all_services() {
        // Verify the constant covers all expected services
        let services: Vec<&str> = PORT_MAPPINGS.iter().map(|&(s, _, _)| s).collect();
        assert!(services.contains(&"postgres"));
        assert!(services.contains(&"rabbitmq"));
        assert!(services.contains(&"keycloak"));
        assert!(services.contains(&"canopy-web"));
        assert!(services.contains(&"canopy-snap"));
        assert!(services.contains(&"canopy-tanf"));
        assert!(services.contains(&"canopy-medicaid"));
        assert!(services.contains(&"canopy-caps"));
        assert!(services.contains(&"canopy-wic"));
    }
}

Step 9: Documentation updates

Files: .claude/docs/local-dev.md, CHANGELOG.adoc

In .claude/docs/local-dev.md, add a section explaining ephemeral port allocation:

  • cargo xtask dev start now reserves ephemeral ports — no more port conflicts.

  • Ports are written to .ports.env at the workspace root.

  • Other terminals can source .ports.env to access service URLs, or use cargo xtask dev status to see the URL table.

  • To use fixed ports (legacy behavior), set CANOPY_PORT_* env vars before running cargo xtask dev start.

In CHANGELOG.adoc, add an entry under == Unreleased:

  • feat(devstack): ephemeral port allocation — devstack no longer requires fixed ports, enabling multiple simultaneous instances and avoiding port conflicts

  • fix(web): correct TANF/Medicaid internal client URLs from 8005/8006 to 8014/8015

Files Touched

File Change

xtask/src/docker.rs

Add PORT_MAPPINGS constant (31 tuples), port_env_var(), reserve_ports(), discover_port(), discover_all_ports(), compose_output(), export_port_env_vars(), write_ports_env(), load_and_export_ports_env(), mark_ports_status(), get_host_port(), print_url_table(), unit tests. Remove check_port_conflicts() and check_port_available().

xtask/src/cmd/dev.rs

Wire ephemeral port lifecycle into do_start() (reserve → export → start → discover → persist → print). Remove check_port_conflicts() call from Action::Start. Add URL table to Action::Status.

xtask/src/cmd/test.rs

Call load_and_export_ports_env() before integration tests.

xtask/src/cmd/e2e.rs

Call load_and_export_ports_env() at start of run().

docker-compose.yml

Replace 31 hardcoded host port mappings with ${CANOPY_PORT_*:-default} interpolation. Parameterize KC_HOSTNAME and KEYCLOAK_ISSUER in all service environments. Fix TANF/Medicaid URLs in canopy-web environment.

services/canopy-web/src/clients.rs

Fix TANF default URL from http://localhost:8005 to http://localhost:8014. Fix Medicaid default URL from http://localhost:8006 to http://localhost:8015. Update test assertions.

.gitignore

Add .ports.env entry.

.claude/docs/local-dev.md

Document ephemeral port allocation, .ports.env file, and fixed-port override pattern.

CHANGELOG.adoc

Add entries for ephemeral ports feature and TANF/Medicaid URL fix.

Verification

  1. cargo nextest run --workspace --lib — unit tests pass (including new port naming + uniqueness tests)

  2. cargo xtask dev start --shared-db — starts with ephemeral ports, prints URL table, creates .ports.env

  3. Verify .ports.env contains all CANOPY_PORT_* vars, KC_HOSTNAME, KEYCLOAK_ISSUER, CANOPY_TEST__*_URL vars, and DEVSTACK_STATUS=ready

  4. In a second terminal: cargo xtask dev status — loads .ports.env and shows URL table with correct ephemeral ports

  5. cargo nextest run --workspace — integration tests pass using discovered ports

  6. cargo xtask e2e — E2E tests pass with ephemeral base URL

  7. Start a second workspace instance from a different checkout — both devstacks start without port conflicts

  8. docker compose up without xtask — falls back to default ports (backward compatibility)

  9. Verify canopy-web TANF/Medicaid requests route to the correct services (ports 8014/8015, not 8005/8006)

Documentation Updates

  • .claude/docs/local-dev.md — ephemeral port allocation section, .ports.env explanation, fixed-port override pattern

  • CHANGELOG.adoc — entry under == Unreleased for ephemeral ports and TANF/Medicaid URL fix

  • .claude/CLAUDE.md — no changes needed (xtask commands unchanged)

  • .claude/docs/services.md — no changes (port numbers are container-internal, unchanged)

Edit this page · default