feat(cli): pic triggers ls --group + group-template journeys + docs (§11 tail T4)

- apply_service: trigger_report(group) → TriggerTemplateInfo
  (kind/target/script/enabled); resolve_inherited_targets_for(Group) now
  surfaces the group's OWN endpoint scripts so a template's handler
  validates (fixes "binds to unknown script" when the handler is a
  pre-existing group script, not declared in the same manifest).
- apply_api: GET /groups/{id}/triggers (GroupScriptsRead).
- CLI: `pic triggers ls --group <g>` (--app/--group mutually exclusive)
  + the client method + DTO.
- tests/group_trigger_templates.rs (manager-core, live DB): the chain
  union matches a descendant app's kv insert against the group template
  and NOT a sibling subtree — the isolation boundary, deterministic.
- tests/group_triggers.rs (journey): apply a kv template, ls --group
  shows it, re-apply NoOp, cron-on-group rejected.
- docs: design §4.5 (live-event-kinds decision + deferrals), CLAUDE.md.

Full journey suite 119/119; workspace tests 0 failures; clippy -D clean;
schema unchanged (blessed in T1).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
MechaCat02
2026-06-30 21:02:03 +02:00
parent 72802de644
commit c492a08775
10 changed files with 519 additions and 10 deletions

View File

@@ -18,7 +18,7 @@ use serde_json::json;
use crate::app_repo::AppRepository;
use crate::apply_service::{
ApplyError, ApplyOwner, ApplyReport, ApplyService, Bundle, BundleTrigger, CollectionInfo,
ExtensionPointInfo, NodeKind, PlanResult, TreeBundle, TreePlanResult,
ExtensionPointInfo, NodeKind, PlanResult, TreeBundle, TreePlanResult, TriggerTemplateInfo,
};
use crate::authz::{require, AuthzDenied, Capability};
use crate::group_repo::GroupRepository;
@@ -41,9 +41,30 @@ pub fn apply_router(service: ApplyService) -> Router {
get(group_extension_points_handler),
)
.route("/groups/{id}/collections", get(group_collections_handler))
.route("/groups/{id}/triggers", get(group_triggers_handler))
.with_state(service)
}
/// Read-only §11 tail trigger-template report for a group: its own declared
/// event trigger templates (kind, target, handler script, enabled). Viewer-tier
/// read. Backs `pic triggers ls --group`.
async fn group_triggers_handler(
State(svc): State<ApplyService>,
Extension(principal): Extension<Principal>,
Path(id_or_slug): Path<String>,
) -> Result<Json<Vec<TriggerTemplateInfo>>, ApplyError> {
let group_id = resolve_group_id(svc.groups.as_ref(), &id_or_slug).await?;
require(
svc.authz.as_ref(),
&principal,
Capability::GroupScriptsRead(group_id),
)
.await
.map_err(map_authz)?;
let report = svc.trigger_report(ApplyOwner::Group(group_id)).await?;
Ok(Json(report))
}
/// Read-only §11.6 shared-collection report for a group: its own declared
/// shared KV collection names. Viewer-tier read.
async fn group_collections_handler(

View File

@@ -461,6 +461,17 @@ pub struct CollectionInfo {
pub kind: String,
}
/// One row of the read-only §11 tail trigger-template report (`pic triggers ls
/// --group`). `target` is the kind-specific identity bit (collection glob or
/// topic pattern); `script` is the handler script's name.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TriggerTemplateInfo {
pub kind: String,
pub target: String,
pub script: String,
pub enabled: bool,
}
// ----------------------------------------------------------------------------
// Errors
// ----------------------------------------------------------------------------
@@ -569,7 +580,42 @@ impl ApplyService {
) -> Result<HashMap<String, ScriptId>, ApplyError> {
match owner {
ApplyOwner::App(app_id) => self.resolve_inherited_targets(app_id, bundle).await,
ApplyOwner::Group(_) => Ok(HashMap::new()),
// §11 tail: a group trigger TEMPLATE binds the group's OWN endpoint
// scripts (declared here or pre-existing). Surface the ones a
// template references but the bundle doesn't declare, so
// `validate_bundle` accepts them (the reconcile's name_to_id already
// includes the group's current scripts).
ApplyOwner::Group(group_id) => {
let declared: HashSet<String> = bundle
.scripts
.iter()
.map(|s| s.name.to_lowercase())
.collect();
let referenced: HashSet<String> = bundle
.triggers
.iter()
.map(|t| t.script().to_lowercase())
.collect();
let by_name: HashMap<String, ScriptId> = self
.scripts
.list_for_group(group_id)
.await
.map_err(map_repo)?
.into_iter()
.filter(|s| s.kind == ScriptKind::Endpoint)
.map(|s| (s.name.to_lowercase(), s.id))
.collect();
let mut out = HashMap::new();
for name in referenced {
if declared.contains(&name) {
continue;
}
if let Some(id) = by_name.get(&name) {
out.insert(name, *id);
}
}
Ok(out)
}
}
}
@@ -1842,6 +1888,58 @@ impl ApplyService {
/// collections (`name` + `kind`) declared directly at it. Group-only in
/// practice (the CLI rejects app-declared collections). Backs
/// `pic collections ls`.
/// Read-only §11 tail report: a group's own trigger TEMPLATES, surfaced as
/// (kind, target, handler script name, enabled). The stored `name` is a UUID
/// default for reconcile-created rows, so the semantic bits are shown
/// instead. Backs `pic triggers ls --group`.
pub async fn trigger_report(
&self,
owner: ApplyOwner,
) -> Result<Vec<TriggerTemplateInfo>, ApplyError> {
let ApplyOwner::Group(group_id) = owner else {
return Ok(Vec::new());
};
let triggers = self
.triggers
.list_for_group(group_id)
.await
.map_err(|e| ApplyError::Backend(e.to_string()))?;
let scripts = self
.scripts
.list_for_group(group_id)
.await
.map_err(|e| ApplyError::Backend(e.to_string()))?;
let name_by_id: HashMap<ScriptId, String> =
scripts.iter().map(|s| (s.id, s.name.clone())).collect();
Ok(triggers
.into_iter()
.map(|t| {
let (kind, target) = match &t.details {
TriggerDetails::Kv {
collection_glob, ..
} => ("kv", collection_glob.clone()),
TriggerDetails::Docs {
collection_glob, ..
} => ("docs", collection_glob.clone()),
TriggerDetails::Files {
collection_glob, ..
} => ("files", collection_glob.clone()),
TriggerDetails::Pubsub { topic_pattern } => ("pubsub", topic_pattern.clone()),
TriggerDetails::Cron { .. } => ("cron", String::new()),
TriggerDetails::Queue { queue_name, .. } => ("queue", queue_name.clone()),
TriggerDetails::Email { .. } => ("email", String::new()),
TriggerDetails::DeadLetter { .. } => ("dead_letter", String::new()),
};
TriggerTemplateInfo {
kind: kind.to_string(),
target,
script: name_by_id.get(&t.script_id).cloned().unwrap_or_default(),
enabled: t.enabled,
}
})
.collect())
}
pub async fn collection_report(
&self,
owner: ApplyOwner,

View File

@@ -0,0 +1,170 @@
//! §11 tail integration test: the live chain-union dispatch for group trigger
//! templates. A group-owned kv trigger TEMPLATE must be matched for a
//! **descendant** app (the union via `CHAIN_LEVELS_CTE`) and must NOT be matched
//! for an app in a **sibling** subtree — that walk is the isolation boundary.
//!
//! Deterministic (no async dispatcher) so it pins the security-critical SQL
//! 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::trigger_repo::{PostgresTriggerRepo, TriggerRepo};
use picloud_shared::{AppId, 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!("group_trigger_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
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn group_kv_template_matches_descendant_not_sibling() {
let Some(pool) = pool_or_skip().await else {
return;
};
let sfx = Uuid::new_v4().simple().to_string();
// registered_by principal
let admin = id1(
&pool,
"INSERT INTO admin_users (username, password_hash) VALUES ($1, 'x') RETURNING id",
&format!("gtt-{sfx}"),
)
.await;
// 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!("gtt-g-{sfx}"),
)
.await;
let g2 = id1(
&pool,
"INSERT INTO groups (slug, name) VALUES ($1, $1) RETURNING id",
&format!("gtt-g2-{sfx}"),
)
.await;
// App A under G (descendant); app C under G2 (sibling subtree).
let a: (Uuid,) =
sqlx::query_as("INSERT INTO apps (slug, name, group_id) VALUES ($1, $1, $2) RETURNING id")
.bind(format!("gtt-a-{sfx}"))
.bind(g)
.fetch_one(&pool)
.await
.expect("app A");
let c: (Uuid,) =
sqlx::query_as("INSERT INTO apps (slug, name, group_id) VALUES ($1, $1, $2) RETURNING id")
.bind(format!("gtt-c-{sfx}"))
.bind(g2)
.fetch_one(&pool)
.await
.expect("app C");
// Group-owned handler script under G.
let s: (Uuid,) = sqlx::query_as(
"INSERT INTO scripts (name, source, group_id) VALUES ($1, 'x', $2) RETURNING id",
)
.bind(format!("handler-{sfx}"))
.bind(g)
.fetch_one(&pool)
.await
.expect("group script");
// Group kv trigger TEMPLATE (group_id = G, app_id NULL) + details.
let t: (Uuid,) = sqlx::query_as(
"INSERT INTO triggers \
(group_id, script_id, kind, enabled, dispatch_mode, \
retry_max_attempts, retry_backoff, retry_base_ms, \
registered_by_principal, name) \
VALUES ($1, $2, 'kv', TRUE, 'async', 3, 'exponential', 1000, $3, $4) \
RETURNING id",
)
.bind(g)
.bind(s.0)
.bind(admin)
.bind(format!("tmpl-{sfx}"))
.fetch_one(&pool)
.await
.expect("template trigger");
sqlx::query(
"INSERT INTO kv_trigger_details (trigger_id, collection_glob, ops) \
VALUES ($1, '*', ARRAY['insert'])",
)
.bind(t.0)
.execute(&pool)
.await
.expect("kv details");
let repo = PostgresTriggerRepo::new(pool.clone());
// Descendant app A's kv insert matches the ancestor group's template.
let matched = repo
.list_matching_kv(AppId::from(a.0), "users", KvEventOp::Insert)
.await
.expect("match for A");
assert!(
matched.iter().any(|m| m.trigger_id == t.0.into()),
"a descendant app must match the group's kv template"
);
// Sibling-subtree app C must NOT — the chain union is the isolation boundary.
let none = repo
.list_matching_kv(AppId::from(c.0), "users", KvEventOp::Insert)
.await
.expect("match for C");
assert!(
!none.iter().any(|m| m.trigger_id == t.0.into()),
"a sibling-subtree app must NOT match another subtree's group template"
);
// Cleanup (best-effort; ordering respects the FKs).
let _ = sqlx::query("DELETE FROM triggers WHERE id = $1")
.bind(t.0)
.execute(&pool)
.await;
let _ = sqlx::query("DELETE FROM scripts WHERE id = $1")
.bind(s.0)
.execute(&pool)
.await;
let _ = sqlx::query("DELETE FROM apps WHERE id = ANY($1)")
.bind(vec![a.0, c.0])
.execute(&pool)
.await;
let _ = sqlx::query("DELETE FROM groups WHERE id = ANY($1)")
.bind(vec![g, g2])
.execute(&pool)
.await;
let _ = sqlx::query("DELETE FROM admin_users WHERE id = $1")
.bind(admin)
.execute(&pool)
.await;
}