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:
-
Trusted proxy parsing (#287): The
rate_limit_middlewareincrates/canopy-api/src/lib.rs(lines 335-341) parsesCANOPY_TRUSTED_PROXIESfrom the environment on every request. This reads the env var, splits on commas, trims whitespace, and parses each entry asIpAddron every single HTTP request. This is wasteful and introduces unnecessary latency. The value should be parsed once at startup and stored in an AxumExtension. -
Orchestrator parameter bundling (288): The
determine()function inservices/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 likejurisdiction,persons_base_url, andauth_tokenare configuration that does not change per request. They should be bundled into aDetermineConfigstruct. -
Age calculation centralization (#289): Age is calculated using
(today - dob).num_days() / 365in at least three locations:-
services/canopy-eligibility/src/orchestrator.rsline 105 -
tools/canopy-seed/src/datagen.rslines 728, 1673This 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_PROXIESat startup, store asExtension<TrustedProxies>in the router -
Create
DetermineConfigstruct 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:
-
services/canopy-eligibility/src/orchestrator.rsline 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()); -
tools/canopy-seed/src/datagen.rsline 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; -
tools/canopy-seed/src/datagen.rsline 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
-
Add
TrustedProxiesstruct withfrom_env()andcontains()methods. -
In
ApiServer::router(), callTrustedProxies::from_env()and add asExtensionlayer alongside the rate limiter. -
Update
rate_limit_middlewareto takeExtension<TrustedProxies>instead of readingstd::env::var("CANOPY_TRUSTED_PROXIES")on each call. -
Remove the inline
trusted_proxiesvariable andsplit(',')parsing from the middleware body (lines 335-341). -
Add unit tests:
-
TrustedProxiesfrom empty env var is empty set -
TrustedProxiesfrom"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)
-
Define
DetermineConfig<'a>struct. -
Change
determine()signature from 8 parameters to(db, config, request). -
Update the function body to access
config.registry,config.client,config.verifier,config.jurisdiction,config.persons_base_url,config.auth_token. -
Remove
#[allow(clippy::too_many_arguments)]annotation (line 206). -
Update the route handler call site to construct
DetermineConfigfrom the existing values. -
Update the existing unit tests (
determine_request_deserializes,determine_response_serializes) — these don’t calldetermine()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
-
Create
crates/canopy-common/src/date.rswithage_years(dob, reference_date) → u32. -
Export
pub mod date;fromcrates/canopy-common/src/lib.rs. -
Replace
(Utc::now().date_naive() - birth).num_days() / 365in orchestrator line 105. -
Replace
(sg.reference_date - person.date_of_birth).num_days() / 365in datagen lines 728 and 1673. -
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 |
|---|---|
|
Add |
|
Add |
|
Update |
|
New file: |
|
Export |
|
Replace 2 inline age calculations with |
Verification
-
cargo nextest run --workspace --lib— unit tests pass (including new TrustedProxies, DetermineConfig, and age_years tests) -
cargo xtask dev reload— services start correctly with existing CANOPY_TRUSTED_PROXIES config -
cargo nextest run --workspace— integration tests pass -
cargo clippy --workspace — -D warnings— no new warnings,too_many_argumentssuppression removed -
cargo xtask test— full test battery passes