feat(shared-triggers): visibility + tests + docs (M2.5)

- `shared` column in `pic triggers ls --group` (TriggerTemplateInfo + DTO +
  report + renderer).
- manager-core/tests/shared_triggers.rs: a shared write matches the group's
  shared trigger and NOT a same-named per-app trigger; a per-app write matches
  the app trigger and NOT the shared one (the `shared` flag is the boundary).
- shared_triggers journey: declarative authoring applies, ls --group shows
  shared, an undeclared-collection shared trigger + an app shared trigger are
  rejected.
- docs: §11.6 + CLAUDE.md move shared-collection triggers from Deferred to
  implemented.

Completes M2. (Pre-existing async-dispatcher timing flakes pass in isolation.)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
MechaCat02
2026-07-01 21:05:30 +02:00
parent f04eaed0b7
commit 9a4b83dfcf
8 changed files with 376 additions and 7 deletions

View File

@@ -575,6 +575,8 @@ pub struct TriggerTemplateInfo {
pub enabled: bool,
/// §11 tail: `true` for a sealed (non-suppressible) template.
pub sealed: bool,
/// §11.6: `true` for a shared-collection template.
pub shared: bool,
}
/// One row of the read-only §11 tail route-template report (`pic routes ls
@@ -2173,6 +2175,7 @@ impl ApplyService {
script: name_by_id.get(&t.script_id).cloned().unwrap_or_default(),
enabled: t.enabled,
sealed: t.sealed,
shared: t.shared,
}
})
.collect())

View File

@@ -0,0 +1,192 @@
//! §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 {
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;
}

View File

@@ -1421,6 +1421,9 @@ pub struct TriggerTemplateDto {
/// §11 tail: `true` for a sealed (non-suppressible) template.
#[serde(default)]
pub sealed: bool,
/// §11.6: `true` for a shared-collection template.
#[serde(default)]
pub shared: bool,
}
/// One row of the §11 tail route-template report.

View File

@@ -47,7 +47,7 @@ pub async fn ls_group(group: &str, mode: OutputMode) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
let rows = client.group_triggers_list(group).await?;
let mut table = Table::new(["kind", "target", "script", "enabled", "sealed"]);
let mut table = Table::new(["kind", "target", "script", "enabled", "sealed", "shared"]);
for t in rows {
table.row([
t.kind,
@@ -55,6 +55,7 @@ pub async fn ls_group(group: &str, mode: OutputMode) -> Result<()> {
t.script,
t.enabled.to_string(),
t.sealed.to_string(),
t.shared.to_string(),
]);
}
table.print(mode);

View File

@@ -43,6 +43,7 @@ mod routes;
mod scripts;
mod sealed;
mod secrets;
mod shared_triggers;
mod staleness;
mod suppress;
mod tree;

View File

@@ -0,0 +1,157 @@
//! §11.6 — shared-collection triggers, declarative authoring end to end via
//! `pic`. A group declares a shared kv collection + a `[[triggers.kv]]
//! shared = true` handler watching it; the template applies, `pic triggers ls
//! --group` shows `shared = true`; a shared trigger on an UNDECLARED collection
//! is rejected, and `shared = true` on an app trigger is rejected.
//!
//! The live FIRING (a shared write matches the shared trigger, a per-app write
//! does not) is pinned deterministically by
//! `manager-core/tests/shared_triggers.rs` — driving the async dispatcher from a
//! journey is deliberately avoided (codebase norm).
use std::fs;
use tempfile::TempDir;
use crate::common;
use crate::common::cleanup::{AppGuard, GroupGuard, ScriptGuard};
fn manifest_dir() -> TempDir {
let dir = TempDir::new().expect("tempdir");
fs::create_dir_all(dir.path().join("scripts")).expect("scripts dir");
dir
}
fn group_script_id(env: &common::TestEnv, group: &str, name: &str) -> String {
let ls = common::pic_as(env)
.args(["scripts", "ls", "--group", group])
.output()
.expect("scripts ls");
let table = String::from_utf8(ls.stdout).unwrap();
table
.lines()
.map(common::cells)
.find(|c| c.get(2) == Some(&name))
.and_then(|c| c.first().map(|s| (*s).to_string()))
.unwrap_or_else(|| panic!("group script `{name}` not found:\n{table}"))
}
#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn shared_kv_trigger_applies_lists_and_validates() {
let Some(fx) = common::fixture_or_skip() else {
return;
};
let env = common::admin_env(fx);
let group = common::unique_slug("shtrig-grp");
let _g = GroupGuard::new(&env.url, &env.token, &group);
common::pic_as(&env)
.args(["groups", "create", &group])
.assert()
.success();
// Group handler for the shared collection.
let dir = manifest_dir();
fs::write(
dir.path().join("scripts/on-cat.rhai"),
r#"log::info("shared catalog write"); "ok""#,
)
.unwrap();
common::pic_as(&env)
.args(["scripts", "deploy"])
.arg(dir.path().join("scripts/on-cat.rhai"))
.args(["--group", &group, "--name", "on-cat"])
.assert()
.success();
let _gs = ScriptGuard::new(
&env.url,
&env.token,
&group_script_id(&env, &group, "on-cat"),
);
// Group declares a shared kv collection `catalog` + a shared kv trigger.
let gmanifest = format!(
"[group]\nslug = \"{group}\"\nname = \"ShTrigG\"\n\
collections = [{{ name = \"catalog\", kind = \"kv\" }}]\n\n\
[[triggers.kv]]\nscript = \"on-cat\"\ncollection_glob = \"catalog\"\nshared = true\n"
);
let gpath = dir.path().join("group.toml");
fs::write(&gpath, &gmanifest).unwrap();
common::pic_as(&env)
.args(["apply", "--file"])
.arg(&gpath)
.assert()
.success();
// `pic triggers ls --group` shows shared = true for the kv trigger.
let ls = String::from_utf8(
common::pic_as(&env)
.args(["triggers", "ls", "--group", &group])
.output()
.unwrap()
.stdout,
)
.unwrap();
let row = ls
.lines()
.map(common::cells)
.find(|c| c.contains(&"on-cat"))
.unwrap_or_else(|| panic!("no on-cat trigger row:\n{ls}"));
assert!(
row.contains(&"true"),
"the shared column must read true for the shared trigger:\n{ls}"
);
// A shared trigger on a collection the group does NOT declare shared is
// rejected at apply.
let bad_group = format!(
"[group]\nslug = \"{group}\"\nname = \"ShTrigG\"\n\
collections = [{{ name = \"catalog\", kind = \"kv\" }}]\n\n\
[[triggers.kv]]\nscript = \"on-cat\"\ncollection_glob = \"undeclared\"\nshared = true\n"
);
fs::write(&gpath, &bad_group).unwrap();
let out = common::pic_as(&env)
.args(["apply", "--file"])
.arg(&gpath)
.output()
.expect("apply bad");
assert!(
!out.status.success(),
"a shared trigger on an undeclared collection must be rejected"
);
// `shared = true` on an APP trigger is rejected.
let app = common::unique_slug("shtrig-app");
let _a = AppGuard::new(&env.url, &env.token, &app);
common::pic_as(&env)
.args(["apps", "create", &app])
.assert()
.success();
fs::write(
dir.path().join("scripts/app-h.rhai"),
r#"log::info("app"); "ok""#,
)
.unwrap();
let amanifest = format!(
"[app]\nslug = \"{app}\"\nname = \"App\"\n\n\
[[scripts]]\nname = \"app-h\"\nfile = \"scripts/app-h.rhai\"\n\n\
[[triggers.kv]]\nscript = \"app-h\"\ncollection_glob = \"widgets\"\nshared = true\n"
);
let apath = dir.path().join("app.toml");
fs::write(&apath, &amanifest).unwrap();
let out = common::pic_as(&env)
.args(["apply", "--file"])
.arg(&apath)
.output()
.expect("apply app");
assert!(
!out.status.success(),
"a shared trigger on an app is rejected (apps don't own shared collections)"
);
let err = String::from_utf8_lossy(&out.stderr);
assert!(
err.to_lowercase().contains("shared"),
"the rejection must mention shared:\n{err}"
);
}