Files
PiCloud/crates/manager-core/tests/group_route_templates.rs
MechaCat02 345db4a076 test: close the DB-suite hermeticity + vacuous-skip gaps
Three related fixes from the test audit.

**The CLI journey fixture gets its own database.** It spawned a real picloud —
whose dispatcher/orchestrator claim loops are global by design (one instance owns
one database) — against the shared dev DB, so it could claim the manager-core
suites' outbox/workflow rows (the same class of bug already fixed for the e2e
suites, one binary over). It now clones one dedicated database per journey run
from the migrated template. test-support gains `named_test_db_url` (explicit
stable name) + a blocking wrapper for the sync `LazyLock` fixture. The one journey
that talks to Postgres directly (dead-letter injection) now uses the fixture's DB
URL, not the base DATABASE_URL, so it hits the database the server reads.

**workflow_orchestrator moves to per-test databases.** Its `claim_ready_step` is
global, so the old harness serialized every test behind a process-wide CLAIM_LOCK
AND ran `DELETE FROM workflow_runs` (unscoped — it wiped every app's runs) before
each one. A private database per test makes the global claim see only that test's
rows, so both the lock and the unscoped DELETE are deleted.

**DB-backed suites fail loud instead of skipping green.** ~15 manager-core suites
`return None` when DATABASE_URL is unset and report PASS — so in any environment
that lost its database the entire integration surface reports green while running
nothing (why the CI gap went unnoticed for so long). New
`picloud_test_support::abort_if_db_required` panics when `PICLOUD_REQUIRE_DB` is
set (CI now sets it) but DATABASE_URL is not, injected into each suite's skip
path. Local runs without the var still skip cleanly.

Mutation-verified: with PICLOUD_REQUIRE_DB=1 and DATABASE_URL unset, a suite
panics; without the var it skips.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 19:39:13 +02:00

222 lines
7.5 KiB
Rust

//! §11 tail integration test: the live expansion of group ROUTE templates into
//! per-app match slices. A group-owned route TEMPLATE must land in the compiled
//! slice of a **descendant** app and must NOT land in an app in a **sibling**
//! subtree — the ancestor-chain expansion is the isolation boundary. An app's
//! own route with an identical binding must **shadow** the template (nearest
//! owner wins); a non-identical app route must **coexist**.
//!
//! Deterministic: drives `list_effective` + `compile_effective_routes` directly
//! (no async dispatcher), pinning the security-critical SQL + the shadow rule
//! without flakiness. Skips cleanly when `DATABASE_URL` is unset.
#![allow(
clippy::needless_pass_by_value,
clippy::many_single_char_names,
clippy::too_many_lines
)]
use picloud_manager_core::route_admin::compile_effective_routes;
use picloud_manager_core::route_repo::{PostgresRouteRepository, RouteRepository};
use picloud_shared::AppId;
use sqlx::postgres::PgPoolOptions;
use sqlx::PgPool;
use uuid::Uuid;
async fn pool_or_skip() -> Option<PgPool> {
let Ok(url) = std::env::var("DATABASE_URL") else {
picloud_test_support::abort_if_db_required("group_route_templates");
eprintln!("group_route_templates: DATABASE_URL unset — skipping");
return None;
};
let pool = PgPoolOptions::new()
.max_connections(2)
.connect(&url)
.await
.expect("connect to DATABASE_URL");
sqlx::migrate!("./migrations")
.run(&pool)
.await
.expect("apply migrations");
Some(pool)
}
async fn id1(pool: &PgPool, sql: &str, bind: &str) -> Uuid {
let row: (Uuid,) = sqlx::query_as(sql)
.bind(bind)
.fetch_one(pool)
.await
.expect("insert returning id");
row.0
}
async fn app_under(pool: &PgPool, slug: &str, group: Uuid) -> Uuid {
let row: (Uuid,) =
sqlx::query_as("INSERT INTO apps (slug, name, group_id) VALUES ($1, $1, $2) RETURNING id")
.bind(slug)
.bind(group)
.fetch_one(pool)
.await
.expect("app insert");
row.0
}
/// The compiled match slice for `app` — its own routes plus inherited
/// ancestor-group templates, after nearest-wins shadowing.
async fn slice_paths(repo: &PostgresRouteRepository, app: Uuid) -> Vec<(String, Uuid)> {
let effective = repo.list_effective().await.expect("list_effective");
let mut suppressed: std::collections::HashMap<(AppId, String), i32> =
std::collections::HashMap::new();
for (a, p, d) in repo
.list_route_suppressions()
.await
.expect("list_route_suppressions")
{
suppressed
.entry((a, p))
.and_modify(|x| *x = (*x).min(d))
.or_insert(d);
}
compile_effective_routes(&effective, &suppressed)
.into_iter()
.filter(|c| c.app_id == AppId::from(app))
.map(|c| {
// PathPattern's Debug carries the raw path; pair it with the bound
// script so the shadow assertion can check which handler won.
(format!("{:?}", c.path), c.script_id.into_inner())
})
.collect()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn group_route_template_expands_to_descendant_not_sibling_and_shadows() {
let Some(pool) = pool_or_skip().await else {
return;
};
let sfx = Uuid::new_v4().simple().to_string();
// G owns the template; G2 is an unrelated sibling subtree.
let g = id1(
&pool,
"INSERT INTO groups (slug, name) VALUES ($1, $1) RETURNING id",
&format!("grt-g-{sfx}"),
)
.await;
let g2 = id1(
&pool,
"INSERT INTO groups (slug, name) VALUES ($1, $1) RETURNING id",
&format!("grt-g2-{sfx}"),
)
.await;
// App A under G (descendant); app C under G2 (sibling subtree).
let a = app_under(&pool, &format!("grt-a-{sfx}"), g).await;
let c = app_under(&pool, &format!("grt-c-{sfx}"), g2).await;
// Group-owned handler script + a group route TEMPLATE binding it.
let group_script: (Uuid,) = sqlx::query_as(
"INSERT INTO scripts (name, source, group_id) VALUES ($1, 'x', $2) RETURNING id",
)
.bind(format!("ghandler-{sfx}"))
.bind(g)
.fetch_one(&pool)
.await
.expect("group script");
sqlx::query(
"INSERT INTO routes (group_id, script_id, host_kind, host, path_kind, path, method) \
VALUES ($1, $2, 'any', '', 'exact', '/hello', NULL)",
)
.bind(g)
.bind(group_script.0)
.execute(&pool)
.await
.expect("group route template");
let repo = PostgresRouteRepository::new(pool.clone());
// Descendant app A's slice CONTAINS the template, bound to the group script.
let a_slice = slice_paths(&repo, a).await;
assert!(
a_slice
.iter()
.any(|(p, sid)| p.contains("/hello") && *sid == group_script.0),
"a descendant app must inherit the group route template:\n{a_slice:?}"
);
// Sibling-subtree app C's slice does NOT — the chain expansion is the bound.
let c_slice = slice_paths(&repo, c).await;
assert!(
!c_slice.iter().any(|(p, _)| p.contains("/hello")),
"a sibling-subtree app must NOT inherit another subtree's template:\n{c_slice:?}"
);
// A's OWN /hello route (its own app-owned script) must SHADOW the template:
// exactly one compiled /hello for A, bound to the app script, not the group.
let app_script: (Uuid,) = sqlx::query_as(
"INSERT INTO scripts (name, source, app_id) VALUES ($1, 'x', $2) RETURNING id",
)
.bind(format!("ahandler-{sfx}"))
.bind(a)
.fetch_one(&pool)
.await
.expect("app script");
sqlx::query(
"INSERT INTO routes (app_id, script_id, host_kind, host, path_kind, path, method) \
VALUES ($1, $2, 'any', '', 'exact', '/hello', NULL)",
)
.bind(a)
.bind(app_script.0)
.execute(&pool)
.await
.expect("app route shadow");
let a_after = slice_paths(&repo, a).await;
let hellos: Vec<_> = a_after
.iter()
.filter(|(p, _)| p.contains("/hello"))
.collect();
assert_eq!(
hellos.len(),
1,
"nearest-wins shadowing must leave exactly one /hello for A:\n{a_after:?}"
);
assert_eq!(
hellos[0].1, app_script.0,
"the app's own route must win over the inherited group template"
);
// A non-identical app route (different path) must COEXIST with the template.
sqlx::query(
"INSERT INTO routes (app_id, script_id, host_kind, host, path_kind, path, method) \
VALUES ($1, $2, 'any', '', 'exact', '/own', NULL)",
)
.bind(a)
.bind(app_script.0)
.execute(&pool)
.await
.expect("app route coexist");
let a_final = slice_paths(&repo, a).await;
assert!(
a_final.iter().any(|(p, _)| p.contains("/own")),
"a non-identical app route must coexist with the inherited template:\n{a_final:?}"
);
// Cleanup (FK order: routes → scripts → apps → groups).
let _ = sqlx::query("DELETE FROM routes WHERE app_id = ANY($1) OR group_id = $2")
.bind(vec![a, c])
.bind(g)
.execute(&pool)
.await;
let _ = sqlx::query("DELETE FROM scripts WHERE id = ANY($1)")
.bind(vec![group_script.0, app_script.0])
.execute(&pool)
.await;
let _ = sqlx::query("DELETE FROM apps WHERE id = ANY($1)")
.bind(vec![a, c])
.execute(&pool)
.await;
let _ = sqlx::query("DELETE FROM groups WHERE id = ANY($1)")
.bind(vec![g, g2])
.execute(&pool)
.await;
}