feat(cli): pic routes ls --group + group-route journey + docs (§11 tail R5)

Visibility + end-to-end coverage + docs for group route templates.

- ApplyService::route_report(Group) → GET /api/v1/admin/groups/{id}/routes
  (viewer-tier GroupScriptsRead), surfacing a group's own route templates
  (method, host, path, handler script, dispatch, enabled).
- CLI: `pic routes ls --group <g>` (the script-id positional now conflicts
  with --group), client `group_routes_list` + RouteTemplateDto.
- Journey `group_routes.rs`: a group declares a `[[routes]]` template
  binding a group handler; a DESCENDANT app serves it (via `routes match`
  against the live RouteTable), a SIBLING-subtree app does not, `routes ls
  --group` shows it, re-apply is a NoOp. Shadowing + isolation are
  additionally pinned at the repo layer by group_route_templates.rs.
- Update the manifest unit test: a [group] now accepts route templates and
  rejects only the stateful trigger kinds.
- Docs: design §4.5 (the live route-template model + full-live
  invalidation + nearest-wins shadowing + deferrals), CLAUDE.md focus.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
MechaCat02
2026-06-30 22:03:59 +02:00
parent 8f1ba39a8a
commit a977ff6a32
10 changed files with 345 additions and 14 deletions

View File

@@ -18,7 +18,8 @@ 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, TriggerTemplateInfo,
ExtensionPointInfo, NodeKind, PlanResult, RouteTemplateInfo, TreeBundle, TreePlanResult,
TriggerTemplateInfo,
};
use crate::authz::{require, AuthzDenied, Capability};
use crate::group_repo::GroupRepository;
@@ -42,9 +43,30 @@ pub fn apply_router(service: ApplyService) -> Router {
)
.route("/groups/{id}/collections", get(group_collections_handler))
.route("/groups/{id}/triggers", get(group_triggers_handler))
.route("/groups/{id}/routes", get(group_routes_handler))
.with_state(service)
}
/// Read-only §11 tail route-template report for a group: its own declared route
/// templates (method, host, path, handler script, dispatch, enabled). Viewer-
/// tier read. Backs `pic routes ls --group`.
async fn group_routes_handler(
State(svc): State<ApplyService>,
Extension(principal): Extension<Principal>,
Path(id_or_slug): Path<String>,
) -> Result<Json<Vec<RouteTemplateInfo>>, 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.route_report(ApplyOwner::Group(group_id)).await?;
Ok(Json(report))
}
/// 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`.

View File

@@ -472,6 +472,21 @@ pub struct TriggerTemplateInfo {
pub enabled: bool,
}
/// One row of the read-only §11 tail route-template report (`pic routes ls
/// --group`). The binding tuple a descendant app inherits, plus the handler
/// script's name. The stored route `name` is a UUID for reconcile-created
/// rows, so the semantic bits are shown instead.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RouteTemplateInfo {
pub method: String,
pub host: String,
pub path_kind: String,
pub path: String,
pub script: String,
pub dispatch: String,
pub enabled: bool,
}
// ----------------------------------------------------------------------------
// Errors
// ----------------------------------------------------------------------------
@@ -1935,6 +1950,46 @@ impl ApplyService {
.collect())
}
/// Read-only §11 tail report: a group's own route TEMPLATES, surfaced as
/// the inherited binding tuple + handler script name. Backs
/// `pic routes ls --group`.
pub async fn route_report(
&self,
owner: ApplyOwner,
) -> Result<Vec<RouteTemplateInfo>, ApplyError> {
let ApplyOwner::Group(group_id) = owner else {
return Ok(Vec::new());
};
let routes = self
.routes
.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(routes
.into_iter()
.map(|r| RouteTemplateInfo {
method: r.method.clone().unwrap_or_else(|| "ANY".into()),
host: match r.host_kind {
HostKind::Any => "any".to_string(),
HostKind::Strict => format!("strict:{}", r.host),
HostKind::Wildcard => format!("*.{}", r.host),
},
path_kind: path_kind_str(r.path_kind).to_string(),
path: r.path.clone(),
script: name_by_id.get(&r.script_id).cloned().unwrap_or_default(),
dispatch: r.dispatch_mode.as_str().to_string(),
enabled: r.enabled,
})
.collect())
}
pub async fn collection_report(
&self,
owner: ApplyOwner,

View File

@@ -1360,6 +1360,17 @@ impl Client {
.await?;
decode(resp).await
}
/// `GET /api/v1/admin/groups/{ident}/routes` (§11 tail). Group-only — route
/// templates are declared on groups and inherited by descendant apps.
pub async fn group_routes_list(&self, group_ident: &str) -> Result<Vec<RouteTemplateDto>> {
let ident = seg(group_ident);
let resp = self
.request(Method::GET, &format!("/api/v1/admin/groups/{ident}/routes"))
.send()
.await?;
decode(resp).await
}
}
/// One row of the §11 tail trigger-template report.
@@ -1373,6 +1384,24 @@ pub struct TriggerTemplateDto {
pub enabled: bool,
}
/// One row of the §11 tail route-template report.
#[derive(Debug, Deserialize)]
pub struct RouteTemplateDto {
#[serde(default)]
pub method: String,
#[serde(default)]
pub host: String,
#[serde(default)]
pub path_kind: String,
#[serde(default)]
pub path: String,
#[serde(default)]
pub script: String,
#[serde(default)]
pub dispatch: String,
pub enabled: bool,
}
/// One row of the §11.6 shared-collection report.
#[derive(Debug, Deserialize)]
pub struct CollectionInfoDto {

View File

@@ -35,6 +35,37 @@ pub async fn ls(script_id: &str, mode: OutputMode) -> Result<()> {
Ok(())
}
/// `pic routes ls --group <g>` — read-only view of a group's §11 tail route
/// TEMPLATES (inherited live by every descendant app). Authoring is declarative
/// via the `[group]` manifest `[[routes]]`.
pub async fn ls_group(group: &str, mode: OutputMode) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
let rows = client.group_routes_list(group).await?;
let mut table = Table::new([
"method",
"host",
"path_kind",
"path",
"script",
"dispatch",
"enabled",
]);
for r in rows {
table.row([
r.method,
r.host,
r.path_kind,
r.path,
r.script,
r.dispatch,
r.enabled.to_string(),
]);
}
table.print(mode);
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub async fn create(
script_id: &str,

View File

@@ -821,8 +821,14 @@ impl From<InstanceRoleArg> for picloud_shared::InstanceRole {
#[derive(Subcommand)]
enum RoutesCmd {
/// List routes bound to a script.
Ls { script_id: String },
/// List routes bound to a script, or a group's route TEMPLATES (`--group`).
Ls {
#[arg(conflicts_with = "group", required_unless_present = "group")]
script_id: Option<String>,
/// List the group's §11 tail route templates instead.
#[arg(long)]
group: Option<String>,
},
/// Create a new route. Host defaults to `*` (any). Path-kind
/// defaults to `exact`. Dispatch defaults to `sync`.
@@ -1608,8 +1614,12 @@ async fn main() -> ExitCode {
Err(e) => Err(e),
},
Cmd::Routes {
cmd: RoutesCmd::Ls { script_id },
} => cmds::routes::ls(&script_id, mode).await,
cmd: RoutesCmd::Ls { script_id, group },
} => match (script_id, group) {
(_, Some(group)) => cmds::routes::ls_group(&group, mode).await,
(Some(script_id), None) => cmds::routes::ls(&script_id, mode).await,
(None, None) => Err(anyhow::anyhow!("provide a script id or --group")),
},
Cmd::Routes {
cmd:
RoutesCmd::Create {

View File

@@ -762,13 +762,22 @@ mod tests {
assert_eq!(m.slug(), "acme");
assert_eq!(m.scripts.len(), 1);
// A group cannot carry routes/triggers.
let err = Manifest::parse(
// §11 tail: a group MAY carry ROUTE templates (inherited by descendants).
let routed = Manifest::parse(
"[group]\nslug = \"acme\"\nname = \"ACME\"\n\n\
[[routes]]\nscript = \"shared\"\nhost_kind = \"any\"\npath_kind = \"exact\"\npath = \"/x\"\n",
)
.expect_err("group with routes is rejected");
assert!(err.to_string().contains("routes"), "got: {err}");
.expect("group with a route template parses");
assert!(routed.is_group());
assert_eq!(routed.routes.len(), 1);
// ...but a STATEFUL trigger kind (cron/queue/email) on a group is rejected.
let err = Manifest::parse(
"[group]\nslug = \"acme\"\nname = \"ACME\"\n\n\
[[triggers.cron]]\nscript = \"shared\"\nschedule = \"0 0 * * * *\"\n",
)
.expect_err("group with a cron trigger is rejected");
assert!(err.to_string().contains("event kind"), "got: {err}");
// Neither / both is rejected.
Manifest::parse("[vars]\nx = 1\n").expect_err("no [app] or [group]");

View File

@@ -26,6 +26,7 @@ mod enabled;
mod env_overlay;
mod extension_points;
mod group_modules;
mod group_routes;
mod group_scripts;
mod group_secrets;
mod group_triggers;

View File

@@ -0,0 +1,154 @@
//! §11 tail — group ROUTE templates, declarative authoring + live inheritance
//! end to end via `pic`. A group declares a `[[routes]]` template binding a
//! group-owned handler; the template is served by a **descendant** app's route
//! table (verified via `routes match`, which queries the live in-memory
//! `RouteTable`), is NOT served by a **sibling**-subtree app, `pic routes ls
//! --group` shows it, and re-apply is a NoOp.
//!
//! Nearest-wins shadowing (an app's own identical route beats the inherited
//! template) and the sibling isolation are pinned deterministically at the repo
//! layer by `manager-core/tests/group_route_templates.rs`; this journey
//! exercises the authoring + the orchestrator dispatch path the operator uses.
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
}
/// Id of the named script in a group (`pic scripts ls --group <g>`).
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}"))
}
/// `routes match` against an app — true iff a route matched the URL.
fn route_matches(env: &common::TestEnv, app: &str, url: &str) -> bool {
let out = common::pic_as(env)
.args(["routes", "match", "--app", app, url])
.output()
.expect("routes match");
let stdout = String::from_utf8(out.stdout).unwrap();
stdout.contains("matched") && stdout.contains("true")
}
#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn group_route_template_serves_descendant_and_lists() {
let Some(fx) = common::fixture_or_skip() else {
return;
};
let env = common::admin_env(fx);
let group = common::unique_slug("grt-grp");
let _g = GroupGuard::new(&env.url, &env.token, &group);
common::pic_as(&env)
.args(["groups", "create", &group])
.assert()
.success();
// A group-owned handler script the route template binds.
let dir = manifest_dir();
fs::write(
dir.path().join("scripts/ghello.rhai"),
r#"log::info("group route fired"); "ok""#,
)
.unwrap();
common::pic_as(&env)
.args(["scripts", "deploy"])
.arg(dir.path().join("scripts/ghello.rhai"))
.args(["--group", &group, "--name", "ghello"])
.assert()
.success();
let _gs = ScriptGuard::new(
&env.url,
&env.token,
&group_script_id(&env, &group, "ghello"),
);
// The group declares a route TEMPLATE binding the handler.
let gmanifest = format!(
"[group]\nslug = \"{group}\"\nname = \"GRoutes\"\n\n\
[[routes]]\nscript = \"ghello\"\npath = \"/ghello\"\npath_kind = \"exact\"\n\
host_kind = \"any\"\n"
);
let gpath = dir.path().join("group.toml");
fs::write(&gpath, &gmanifest).unwrap();
common::pic_as(&env)
.args(["apply", "--file"])
.arg(&gpath)
.assert()
.success();
// `routes ls --group` shows the template (path + handler).
let ls = String::from_utf8(
common::pic_as(&env)
.args(["routes", "ls", "--group", &group])
.output()
.unwrap()
.stdout,
)
.unwrap();
assert!(
ls.contains("/ghello") && ls.contains("ghello"),
"routes ls --group should list the template binding ghello:\n{ls}"
);
// Re-apply is a NoOp (the template marker already exists).
let report = String::from_utf8(
common::pic_as(&env)
.args(["apply", "--file"])
.arg(&gpath)
.output()
.unwrap()
.stdout,
)
.unwrap();
assert!(
!report.contains("route")
|| report.to_lowercase().contains("no changes")
|| report.contains('0'),
"re-apply should not create a second template:\n{report}"
);
// A DESCENDANT app under the group serves the inherited template.
let blog = common::unique_slug("grt-blog");
let _ba = AppGuard::new(&env.url, &env.token, &blog);
common::pic_as(&env)
.args(["apps", "create", &blog, "--group", &group])
.assert()
.success();
assert!(
route_matches(&env, &blog, "http://localhost/ghello"),
"a descendant app must serve the inherited group route template"
);
// A SIBLING-subtree app (created at the instance root, not under the group)
// must NOT serve it — the chain expansion is the isolation boundary.
let other = common::unique_slug("grt-other");
let _oa = AppGuard::new(&env.url, &env.token, &other);
common::pic_as(&env)
.args(["apps", "create", &other])
.assert()
.success();
assert!(
!route_matches(&env, &other, "http://localhost/ghello"),
"a sibling-subtree app must NOT serve another subtree's route template"
);
}