Plan: Minor Refactors

Status

Step Description Status

1

Parse CANOPY_TRUSTED_PROXIES once at startup, store in Extension

Done (2026-04-09) — TrustedProxies struct parsed at startup, stored as Extension, used by rate_limit_middleware

2

Bundle orchestrator determine() parameters into DetermineConfig

Done (2026-04-09) — DetermineConfig<'a> struct with registry, client, verifier, jurisdiction, persons_base_url, auth_token

3

Centralize age calculation into canopy-common utility

Done (2026-04-09) — (canopy_common::date::age_years, MR !50)

Epic: TBD
Issues: #287, #288, #289
Branch: refactor/minor-quality

Context

Three independent code quality improvements, each small enough to bundle into a single branch:

  1. Trusted proxy parsing (#287): The rate_limit_middleware in crates/canopy-api/src/lib.rs (lines 335-341) parses CANOPY_TRUSTED_PROXIES from the environment on every request. This reads the env var, splits on commas, trims whitespace, and parses each entry as IpAddr on every single HTTP request. This is wasteful and introduces unnecessary latency. The value should be parsed once at startup and stored in an Axum Extension.

  2. Orchestrator parameter bundling (288): The determine() function in services/canopy-eligibility/src/orchestrator.rs (line 207) takes 8 parameters and is annotated with [allow(clippy::too_many_arguments)]. This is a code smell. Parameters like jurisdiction, persons_base_url, and auth_token are configuration that does not change per request. They should be bundled into a DetermineConfig struct.

  3. Age calculation centralization (#289): Age is calculated using (today - dob).num_days() / 365 in at least three locations:

    • services/canopy-eligibility/src/orchestrator.rs line 105

    • tools/canopy-seed/src/datagen.rs lines 728, 1673

      This integer division is imprecise (off-by-one on leap year boundaries). A centralized `canopy_common::age_years(dob, reference_date)` function using `chrono::NaiveDate::years_since()` would be more accurate and DRY.

Scope

In scope:

  • Parse CANOPY_TRUSTED_PROXIES at startup, store as Extension<TrustedProxies> in the router

  • Create DetermineConfig struct bundling orchestrator determine() parameters

  • Create canopy_common::date::age_years() utility function

  • Replace all inline age calculations with the centralized function

Out of scope:

  • Refactoring other middleware (auth, idempotency) — they already follow good patterns

  • Refactoring other function signatures across services

  • Performance benchmarking of the trusted proxy change

Design

TrustedProxies Extension (#287)

Create a new type in crates/canopy-api/src/lib.rs:

/// Parsed set of trusted proxy IP addresses.
/// Parsed once at startup from CANOPY_TRUSTED_PROXIES environment variable.
#[derive(Clone)]
pub struct TrustedProxies(pub std::collections::HashSet<std::net::IpAddr>);

impl TrustedProxies {
    pub fn from_env() -> Self {
        let raw = std::env::var("CANOPY_TRUSTED_PROXIES").unwrap_or_default();
        let proxies: std::collections::HashSet<std::net::IpAddr> = raw
            .split(',')
            .filter_map(|s| s.trim().parse().ok())
            .collect();
        if !proxies.is_empty() {
            tracing::info!(count = proxies.len(), "trusted proxies configured");
        }
        Self(proxies)
    }

    pub fn contains(&self, ip: &std::net::IpAddr) -> bool {
        self.0.contains(ip)
    }
}

In ApiServer::router() (line 81), create the TrustedProxies and add it as a layer:

let trusted_proxies = TrustedProxies::from_env();
// ... after rate limiter setup ...
protected = protected.layer(axum::Extension(trusted_proxies));

Update rate_limit_middleware (line 323) to extract TrustedProxies instead of reading the env var:

async fn rate_limit_middleware(
    Extension(limiter): Extension<std::sync::Arc<KeyedLimiter>>,
    Extension(proxies): Extension<TrustedProxies>,
    request: axum::extract::Request,
    next: axum::middleware::Next,
) -> axum::response::Response {
    let socket_ip = request
        .extensions()
        .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
        .map(|ci| ci.0.ip());

    let is_trusted_proxy = socket_ip.is_some_and(|s| proxies.contains(&s));
    // ... rest unchanged ...
}

Using HashSet instead of linear scan improves lookup from O(n) to O(1) when multiple proxies are configured.

DetermineConfig struct (#288)

Create a new struct in services/canopy-eligibility/src/orchestrator.rs:

/// Configuration for the eligibility determination pipeline.
/// Bundled to reduce parameter count on determine() (was 8 args).
pub struct DetermineConfig<'a> {
    pub registry: &'a ProgramServiceRegistry,
    pub client: &'a reqwest::Client,
    pub verifier: &'a Arc<VerifyingKeyRegistry>,
    pub jurisdiction: &'a str,
    pub persons_base_url: &'a str,
    pub auth_token: &'a str,
}

Simplify the determine() signature:

pub async fn determine(
    db: &PgPool,
    config: &DetermineConfig<'_>,
    request: DetermineRequest,
) -> Result<DetermineResponse, ApiError> {
    // Access via config.registry, config.client, etc.

Update all call sites (the route handler in services/canopy-eligibility/src/api.rs or equivalent) to construct a DetermineConfig and pass it. Remove the #[allow(clippy::too_many_arguments)] annotation.

Centralized age calculation (#289)

Add a date module to canopy-common:

// crates/canopy-common/src/date.rs

use chrono::NaiveDate;

/// Calculate age in whole years from date of birth to a reference date.
///
/// Uses `years_since()` for leap-year-correct calculation.
/// Returns 0 if `reference_date` is before `dob`.
pub fn age_years(dob: NaiveDate, reference_date: NaiveDate) -> u32 {
    reference_date.years_since(dob).unwrap_or(0)
}

Export from crates/canopy-common/src/lib.rs:

pub mod date;

Replace inline calculations:

  1. services/canopy-eligibility/src/orchestrator.rs line 105:

    // Before:
    let age = (Utc::now().date_naive() - birth).num_days() / 365;
    // After:
    let age = canopy_common::date::age_years(birth, Utc::now().date_naive());
  2. tools/canopy-seed/src/datagen.rs line 728:

    // Before:
    let age_years = (sg.reference_date - person.date_of_birth).num_days() / 365;
    // After:
    let age_years = canopy_common::date::age_years(person.date_of_birth, sg.reference_date) as i64;
  3. tools/canopy-seed/src/datagen.rs line 1673:

    // Before:
    head_person.map(|p| ((sg.reference_date - p.date_of_birth).num_days() / 365) as i32);
    // After:
    head_person.map(|p| canopy_common::date::age_years(p.date_of_birth, sg.reference_date) as i32);

Steps

Step 1: Parse CANOPY_TRUSTED_PROXIES at startup

Files: crates/canopy-api/src/lib.rs

  1. Add TrustedProxies struct with from_env() and contains() methods.

  2. In ApiServer::router(), call TrustedProxies::from_env() and add as Extension layer alongside the rate limiter.

  3. Update rate_limit_middleware to take Extension<TrustedProxies> instead of reading std::env::var("CANOPY_TRUSTED_PROXIES") on each call.

  4. Remove the inline trusted_proxies variable and split(',') parsing from the middleware body (lines 335-341).

  5. Add unit tests:

    • TrustedProxies from empty env var is empty set

    • TrustedProxies from "10.0.0.1, 10.0.0.2" contains both IPs

    • contains() returns false for non-trusted IP

Step 2: Bundle orchestrator determine() parameters

Files: services/canopy-eligibility/src/orchestrator.rs, services/canopy-eligibility/src/api.rs (or route handler file)

  1. Define DetermineConfig<'a> struct.

  2. Change determine() signature from 8 parameters to (db, config, request).

  3. Update the function body to access config.registry, config.client, config.verifier, config.jurisdiction, config.persons_base_url, config.auth_token.

  4. Remove #[allow(clippy::too_many_arguments)] annotation (line 206).

  5. Update the route handler call site to construct DetermineConfig from the existing values.

  6. Update the existing unit tests (determine_request_deserializes, determine_response_serializes) — these don’t call determine() directly so may not need changes.

Step 3: Centralize age calculation

Files: crates/canopy-common/src/date.rs (new), crates/canopy-common/src/lib.rs, services/canopy-eligibility/src/orchestrator.rs, tools/canopy-seed/src/datagen.rs

  1. Create crates/canopy-common/src/date.rs with age_years(dob, reference_date) → u32.

  2. Export pub mod date; from crates/canopy-common/src/lib.rs.

  3. Replace (Utc::now().date_naive() - birth).num_days() / 365 in orchestrator line 105.

  4. Replace (sg.reference_date - person.date_of_birth).num_days() / 365 in datagen lines 728 and 1673.

  5. Add unit tests in date.rs:

    • age_years_exact_birthday — born 2000-01-01, reference 2026-01-01, expect 26

    • age_years_day_before_birthday — born 2000-06-15, reference 2026-06-14, expect 25

    • age_years_leap_year — born 2000-02-29, reference 2026-02-28, expect 25 (or 26 depending on convention)

    • age_years_future_dob — born 2030-01-01, reference 2026-01-01, expect 0

Files Touched

File Change

crates/canopy-api/src/lib.rs

Add TrustedProxies struct, update ApiServer::router() and rate_limit_middleware

services/canopy-eligibility/src/orchestrator.rs

Add DetermineConfig struct, simplify determine() signature, use canopy_common::date::age_years()

services/canopy-eligibility/src/api.rs

Update determine() call site to use DetermineConfig

crates/canopy-common/src/date.rs

New file: age_years() utility function

crates/canopy-common/src/lib.rs

Export pub mod date

tools/canopy-seed/src/datagen.rs

Replace 2 inline age calculations with canopy_common::date::age_years()

Verification

  1. cargo nextest run --workspace --lib — unit tests pass (including new TrustedProxies, DetermineConfig, and age_years tests)

  2. cargo xtask dev reload — services start correctly with existing CANOPY_TRUSTED_PROXIES config

  3. cargo nextest run --workspace — integration tests pass

  4. cargo clippy --workspace — -D warnings — no new warnings, too_many_arguments suppression removed

  5. cargo xtask test — full test battery passes

Documentation Updates

  • .claude/docs/services.md — note DetermineConfig in eligibility orchestrator

  • CHANGELOG.adoc — entry under == Unreleased

  • .claude/docs/coding-conventions.md — document canopy_common::date::age_years() as the canonical age calculation

Edit this page · default