Files
PiCloud/crates/manager-core/tests/shared_triggers.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

194 lines
6.1 KiB
Rust

//! §11.6 integration test: SHARED-collection triggers.
//! A group-owned `shared = true` trigger watches the group's shared collection.
//! A write to that shared collection (by any subtree app) matches the shared
//! trigger via the OWNING-group match query; a per-app collection of the same
//! name does NOT match it, and the shared trigger does NOT match a per-app
//! write (the `shared` flag is the namespace boundary).
//!
//! Deterministic: drives `list_matching_shared_kv` + `list_matching_kv`
//! directly (no async dispatcher). Skips when `DATABASE_URL` is unset.
#![allow(clippy::needless_pass_by_value, clippy::too_many_lines)]
use picloud_manager_core::trigger_repo::{PostgresTriggerRepo, TriggerRepo};
use picloud_shared::{AppId, GroupId, KvEventOp};
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("shared_triggers");
eprintln!("shared_triggers: DATABASE_URL unset — skipping");
return None;
};
let pool = PgPoolOptions::new()
.max_connections(2)
.connect(&url)
.await
.expect("connect");
sqlx::migrate!("./migrations")
.run(&pool)
.await
.expect("migrate");
Some(pool)
}
/// Insert a kv trigger (owner + `shared` flag) + its details; returns id.
async fn kv_trigger(
pool: &PgPool,
app_id: Option<Uuid>,
group_id: Option<Uuid>,
script: Uuid,
admin: Uuid,
shared: bool,
glob: &str,
) -> Uuid {
let row: (Uuid,) = sqlx::query_as(
"INSERT INTO triggers \
(app_id, group_id, script_id, kind, enabled, dispatch_mode, \
retry_max_attempts, retry_backoff, retry_base_ms, \
registered_by_principal, name, shared) \
VALUES ($1, $2, $3, 'kv', TRUE, 'async', 3, 'exponential', 1000, $4, $5, $6) RETURNING id",
)
.bind(app_id)
.bind(group_id)
.bind(script)
.bind(admin)
.bind(Uuid::new_v4().simple().to_string())
.bind(shared)
.fetch_one(pool)
.await
.expect("trigger");
sqlx::query(
"INSERT INTO kv_trigger_details (trigger_id, collection_glob, ops) \
VALUES ($1, $2, ARRAY['insert'])",
)
.bind(row.0)
.bind(glob)
.execute(pool)
.await
.expect("details");
row.0
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shared_trigger_matches_only_shared_writes() {
let Some(pool) = pool_or_skip().await else {
return;
};
let sfx = Uuid::new_v4().simple().to_string();
let admin = {
let r: (Uuid,) = sqlx::query_as(
"INSERT INTO admin_users (username, password_hash) VALUES ($1, 'x') RETURNING id",
)
.bind(format!("sh-{sfx}"))
.fetch_one(&pool)
.await
.unwrap();
r.0
};
// Group G with a handler + a SHARED kv trigger on collection "catalog".
let g: (Uuid,) = sqlx::query_as("INSERT INTO groups (slug, name) VALUES ($1, $1) RETURNING id")
.bind(format!("sh-g-{sfx}"))
.fetch_one(&pool)
.await
.unwrap();
let handler: (Uuid,) = sqlx::query_as(
"INSERT INTO scripts (name, source, group_id) VALUES ($1, 'x', $2) RETURNING id",
)
.bind(format!("on-cat-{sfx}"))
.bind(g.0)
.fetch_one(&pool)
.await
.unwrap();
let shared_trig = kv_trigger(&pool, None, Some(g.0), handler.0, admin, true, "catalog").await;
// App A under G with its OWN (non-shared) kv trigger on "catalog".
let a: (Uuid,) =
sqlx::query_as("INSERT INTO apps (slug, name, group_id) VALUES ($1, $1, $2) RETURNING id")
.bind(format!("sh-a-{sfx}"))
.bind(g.0)
.fetch_one(&pool)
.await
.unwrap();
let app_script: (Uuid,) = sqlx::query_as(
"INSERT INTO scripts (name, source, app_id) VALUES ($1, 'x', $2) RETURNING id",
)
.bind(format!("app-cat-{sfx}"))
.bind(a.0)
.fetch_one(&pool)
.await
.unwrap();
let app_trig = kv_trigger(
&pool,
Some(a.0),
None,
app_script.0,
admin,
false,
"catalog",
)
.await;
let trig = PostgresTriggerRepo::new(pool.clone());
// A SHARED write to G's "catalog" → matches the shared trigger, NOT the
// app's per-app trigger.
let shared_matches = trig
.list_matching_shared_kv(GroupId::from(g.0), "catalog", KvEventOp::Insert)
.await
.expect("shared match");
assert!(
shared_matches
.iter()
.any(|m| m.trigger_id == shared_trig.into()),
"a shared write must match the group's shared trigger"
);
assert!(
!shared_matches
.iter()
.any(|m| m.trigger_id == app_trig.into()),
"a shared write must NOT match a per-app trigger of the same name"
);
// A PER-APP write to app A's "catalog" → matches the app's trigger, NOT the
// shared trigger (the per-app query excludes `shared = TRUE`).
let app_matches = trig
.list_matching_kv(AppId::from(a.0), "catalog", KvEventOp::Insert)
.await
.expect("app match");
assert!(
app_matches.iter().any(|m| m.trigger_id == app_trig.into()),
"a per-app write must match the app's own trigger"
);
assert!(
!app_matches
.iter()
.any(|m| m.trigger_id == shared_trig.into()),
"a per-app write must NOT match the group's shared trigger"
);
// Cleanup.
let _ = sqlx::query("DELETE FROM triggers WHERE id = ANY($1)")
.bind(vec![shared_trig, app_trig])
.execute(&pool)
.await;
let _ = sqlx::query("DELETE FROM apps WHERE id = $1")
.bind(a.0)
.execute(&pool)
.await;
let _ = sqlx::query("DELETE FROM scripts WHERE id = ANY($1)")
.bind(vec![handler.0, app_script.0])
.execute(&pool)
.await;
let _ = sqlx::query("DELETE FROM groups WHERE id = $1")
.bind(g.0)
.execute(&pool)
.await;
let _ = sqlx::query("DELETE FROM admin_users WHERE id = $1")
.bind(admin)
.execute(&pool)
.await;
}