Phase 4-lite C2. Lets a group own scripts (templates inherited by descendant
apps), with the create/list/manage surface — but not yet the inherited
resolution (binding + runtime), which is C3.
Capabilities: add `GroupScriptsRead` (viewer+ on the group → script:read) and
`GroupScriptsWrite` (editor+ → script:write), mirroring the group-vars tier and
resolved through the same group-ancestor walk.
API:
* New `group_scripts_api`: `POST/GET /groups/{id}/scripts` — create a
group-owned endpoint script and list a group's own (non-inherited) rows.
Phase 4-lite is endpoint-only and self-contained: `kind=module` and any
`import` are rejected (group modules + the lexical resolver are Phase 4b).
Owner resolved first (slug-or-uuid); capability bound to the resolved id.
* The by-id `/scripts/{id}` get/update/delete/logs handlers are now
owner-polymorphic via a `script_cap` helper: app-owned scripts gate on
`App*` exactly as before; group-owned on `GroupScripts*`. This is what
makes `deploy --group` idempotent (update reuses the by-id PUT) and lets a
group script be deleted by id. (C1 had these fail closed for groups.)
Repo: `list_for_group(group_id)` (the group's own rows).
CLI: `pic scripts ls --group <g>`, `pic scripts deploy --group <g>` (create or
update by name; `--app`/`--group` are mutually exclusive, exactly one
required). `pic scripts delete <id>` already works for group scripts via the
owner-polymorphic by-id route.
Live-validated against the dev DB: create → update (v2 via the by-id PUT) →
list → delete, plus module rejection and the polymorphic row shape
(`app_id NULL`, `group_id` set). Group scripts still can't be routed/triggered
or invoked — that lands in C3.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1972 lines
61 KiB
Rust
1972 lines
61 KiB
Rust
//! Reqwest-backed HTTP client + minimal wire DTOs.
|
|
//!
|
|
//! The CLI deliberately re-declares small request/response structs here
|
|
//! rather than depending on `manager-core` (and pulling its Postgres
|
|
//! transitive surface). Fields kept to what the CLI actually sends or
|
|
//! reads.
|
|
|
|
use std::collections::BTreeMap;
|
|
|
|
use anyhow::{anyhow, Context, Result};
|
|
use chrono::{DateTime, Utc};
|
|
use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};
|
|
use picloud_shared::{
|
|
AdminUserId, ApiKeyId, App, AppDomain, AppId, AppRole, AppUser, DispatchMode, ExecutionLog,
|
|
Group, HostKind, InstanceRole, PathKind, Route, Scope, Script, ScriptId, ScriptKind,
|
|
ScriptSandbox,
|
|
};
|
|
use reqwest::{header, Method, RequestBuilder, StatusCode};
|
|
use serde::{Deserialize, Serialize};
|
|
use serde_json::Value;
|
|
|
|
use crate::config::Credentials;
|
|
|
|
/// Characters that must be escaped inside a single URL **path segment** so
|
|
/// a free-form value (an app slug, a topic name) can't break out of its
|
|
/// segment — `/` would start a new segment, `?`/`#` would start the query
|
|
/// or fragment. Encodes controls, space, and the structural delimiters.
|
|
const PATH_SEGMENT: &AsciiSet = &CONTROLS
|
|
.add(b' ')
|
|
.add(b'/')
|
|
.add(b'?')
|
|
.add(b'#')
|
|
.add(b'%')
|
|
.add(b'&')
|
|
.add(b'+');
|
|
|
|
/// Percent-encode a value for safe interpolation into one path segment.
|
|
fn seg(s: &str) -> String {
|
|
utf8_percent_encode(s, PATH_SEGMENT).to_string()
|
|
}
|
|
|
|
pub struct Client {
|
|
http: reqwest::Client,
|
|
url: String,
|
|
token: String,
|
|
}
|
|
|
|
impl Client {
|
|
pub fn from_creds(creds: &Credentials) -> Result<Self> {
|
|
Self::new(&creds.url, &creds.token)
|
|
}
|
|
|
|
pub fn new(url: &str, token: &str) -> Result<Self> {
|
|
let http = reqwest::Client::builder()
|
|
.user_agent(concat!("pic/", env!("CARGO_PKG_VERSION")))
|
|
.build()
|
|
.context("building HTTP client")?;
|
|
Ok(Self {
|
|
http,
|
|
url: url.trim_end_matches('/').to_string(),
|
|
token: token.to_string(),
|
|
})
|
|
}
|
|
|
|
#[allow(dead_code)] // used by the trailing-slash unit test below.
|
|
pub fn url(&self) -> &str {
|
|
&self.url
|
|
}
|
|
|
|
fn request(&self, method: Method, path: &str) -> RequestBuilder {
|
|
self.http
|
|
.request(method, format!("{}{path}", self.url))
|
|
.header(header::AUTHORIZATION, format!("Bearer {}", self.token))
|
|
}
|
|
|
|
/// `GET /api/v1/admin/auth/me`
|
|
pub async fn auth_me(&self) -> Result<AuthMeDto> {
|
|
let resp = self
|
|
.request(Method::GET, "/api/v1/admin/auth/me")
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `GET /api/v1/admin/apps`
|
|
pub async fn apps_list(&self) -> Result<Vec<App>> {
|
|
let resp = self
|
|
.request(Method::GET, "/api/v1/admin/apps")
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `GET /api/v1/admin/apps/{id_or_slug}` — slug or UUID accepted.
|
|
pub async fn apps_get(&self, ident: &str) -> Result<AppLookupDto> {
|
|
let ident = seg(ident);
|
|
let resp = self
|
|
.request(Method::GET, &format!("/api/v1/admin/apps/{ident}"))
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `POST /api/v1/admin/apps`
|
|
pub async fn apps_create(&self, body: &CreateAppBody<'_>) -> Result<App> {
|
|
let resp = self
|
|
.request(Method::POST, "/api/v1/admin/apps")
|
|
.json(body)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `GET /api/v1/admin/scripts?app={ident}`
|
|
pub async fn scripts_list_by_app(&self, ident: &str) -> Result<Vec<Script>> {
|
|
let resp = self
|
|
.request(
|
|
Method::GET,
|
|
&format!("/api/v1/admin/scripts?app={}", urlencoded(ident)),
|
|
)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `GET /api/v1/admin/scripts` — every script the caller can see
|
|
/// (server filters by membership for `Member`). Lets `pic scripts ls`
|
|
/// (no `--app`) collapse what used to be an N+1 per-app walk into a
|
|
/// single request that can't be partially-broken by a concurrent app
|
|
/// delete.
|
|
pub async fn scripts_list_all(&self) -> Result<Vec<Script>> {
|
|
let resp = self
|
|
.request(Method::GET, "/api/v1/admin/scripts")
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `DELETE /api/v1/admin/apps/{id_or_slug}` with optional `?force=true`.
|
|
/// Server requires `AppAdmin` capability; without `force`, returns
|
|
/// 409 if the app still has scripts.
|
|
pub async fn apps_delete(&self, ident: &str, force: bool) -> Result<()> {
|
|
let ident = seg(ident);
|
|
let path = if force {
|
|
format!("/api/v1/admin/apps/{ident}?force=true")
|
|
} else {
|
|
format!("/api/v1/admin/apps/{ident}")
|
|
};
|
|
let resp = self.request(Method::DELETE, &path).send().await?;
|
|
decode_status(resp).await
|
|
}
|
|
|
|
// --- Groups (Phase 2) -------------------------------------------------
|
|
|
|
/// `GET /api/v1/admin/groups` — the full flat list (assemble the tree
|
|
/// client-side from `parent_id`).
|
|
pub async fn groups_list(&self) -> Result<Vec<Group>> {
|
|
let resp = self
|
|
.request(Method::GET, "/api/v1/admin/groups")
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `GET /api/v1/admin/groups/{id_or_slug}` — group + path + children.
|
|
pub async fn groups_get(&self, ident: &str) -> Result<GroupDetailDto> {
|
|
let ident = seg(ident);
|
|
let resp = self
|
|
.request(Method::GET, &format!("/api/v1/admin/groups/{ident}"))
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `POST /api/v1/admin/groups`
|
|
pub async fn groups_create(&self, body: &CreateGroupBody<'_>) -> Result<Group> {
|
|
let resp = self
|
|
.request(Method::POST, "/api/v1/admin/groups")
|
|
.json(body)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `PATCH /api/v1/admin/groups/{id_or_slug}` — name/description only
|
|
/// (the slug is frozen).
|
|
pub async fn groups_rename(
|
|
&self,
|
|
ident: &str,
|
|
name: Option<&str>,
|
|
description: Option<&str>,
|
|
) -> Result<Group> {
|
|
let ident = seg(ident);
|
|
let body = serde_json::json!({ "name": name, "description": description });
|
|
let resp = self
|
|
.request(Method::PATCH, &format!("/api/v1/admin/groups/{ident}"))
|
|
.json(&body)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `POST /api/v1/admin/groups/{id_or_slug}/reparent` — `parent` is a
|
|
/// slug/id, or `None` to move to root.
|
|
pub async fn groups_reparent(&self, ident: &str, parent: Option<&str>) -> Result<Group> {
|
|
let ident = seg(ident);
|
|
let body = serde_json::json!({ "parent": parent });
|
|
let resp = self
|
|
.request(
|
|
Method::POST,
|
|
&format!("/api/v1/admin/groups/{ident}/reparent"),
|
|
)
|
|
.json(&body)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `DELETE /api/v1/admin/groups/{id_or_slug}` — 409 if non-empty.
|
|
pub async fn groups_delete(&self, ident: &str) -> Result<()> {
|
|
let ident = seg(ident);
|
|
let resp = self
|
|
.request(Method::DELETE, &format!("/api/v1/admin/groups/{ident}"))
|
|
.send()
|
|
.await?;
|
|
decode_status(resp).await
|
|
}
|
|
|
|
pub async fn group_members_list(&self, group: &str) -> Result<Vec<AppMemberDto>> {
|
|
let group = seg(group);
|
|
let resp = self
|
|
.request(
|
|
Method::GET,
|
|
&format!("/api/v1/admin/groups/{group}/members"),
|
|
)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
pub async fn group_members_grant(
|
|
&self,
|
|
group: &str,
|
|
user_id: &str,
|
|
role: AppRole,
|
|
) -> Result<AppMemberDto> {
|
|
let group = seg(group);
|
|
let body = serde_json::json!({ "user_id": user_id, "role": role });
|
|
let resp = self
|
|
.request(
|
|
Method::POST,
|
|
&format!("/api/v1/admin/groups/{group}/members"),
|
|
)
|
|
.json(&body)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
pub async fn group_members_set_role(
|
|
&self,
|
|
group: &str,
|
|
user_id: &str,
|
|
role: AppRole,
|
|
) -> Result<AppMemberDto> {
|
|
let (group, user_id) = (seg(group), seg(user_id));
|
|
let body = serde_json::json!({ "role": role });
|
|
let resp = self
|
|
.request(
|
|
Method::PATCH,
|
|
&format!("/api/v1/admin/groups/{group}/members/{user_id}"),
|
|
)
|
|
.json(&body)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
pub async fn group_members_remove(&self, group: &str, user_id: &str) -> Result<()> {
|
|
let (group, user_id) = (seg(group), seg(user_id));
|
|
let resp = self
|
|
.request(
|
|
Method::DELETE,
|
|
&format!("/api/v1/admin/groups/{group}/members/{user_id}"),
|
|
)
|
|
.send()
|
|
.await?;
|
|
decode_status(resp).await
|
|
}
|
|
|
|
/// `DELETE /api/v1/admin/scripts/{id}` — requires `AppAdmin` on the
|
|
/// owning app (stricter than the edit endpoints, by design).
|
|
pub async fn scripts_delete(&self, id: &str) -> Result<()> {
|
|
let id = seg(id);
|
|
let resp = self
|
|
.request(Method::DELETE, &format!("/api/v1/admin/scripts/{id}"))
|
|
.send()
|
|
.await?;
|
|
decode_status(resp).await
|
|
}
|
|
|
|
/// `POST /api/v1/admin/scripts`
|
|
pub async fn scripts_create(&self, body: &CreateScriptBody<'_>) -> Result<Script> {
|
|
let resp = self
|
|
.request(Method::POST, "/api/v1/admin/scripts")
|
|
.json(body)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `GET /api/v1/admin/groups/{id_or_slug}/scripts` — a group's own
|
|
/// scripts (Phase 4). Not inherited; just the group's rows.
|
|
pub async fn group_scripts_list(&self, group_ident: &str) -> Result<Vec<Script>> {
|
|
let g = seg(group_ident);
|
|
let resp = self
|
|
.request(Method::GET, &format!("/api/v1/admin/groups/{g}/scripts"))
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `POST /api/v1/admin/groups/{id_or_slug}/scripts` — create a
|
|
/// group-owned script (Phase 4).
|
|
pub async fn group_scripts_create(
|
|
&self,
|
|
group_ident: &str,
|
|
body: &CreateGroupScriptBody<'_>,
|
|
) -> Result<Script> {
|
|
let g = seg(group_ident);
|
|
let resp = self
|
|
.request(Method::POST, &format!("/api/v1/admin/groups/{g}/scripts"))
|
|
.json(body)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `PUT /api/v1/admin/scripts/{id}` — matches the dashboard, which
|
|
/// uses PUT despite the field-level update semantics. `cfg` carries
|
|
/// optional per-script runtime overrides (G3); unset fields are
|
|
/// omitted so they keep their stored value.
|
|
pub async fn scripts_update_source(
|
|
&self,
|
|
id: &str,
|
|
source: &str,
|
|
cfg: &ScriptConfig,
|
|
) -> Result<Script> {
|
|
let id = seg(id);
|
|
let body = UpdateScriptBody {
|
|
source,
|
|
timeout_seconds: cfg.timeout_seconds,
|
|
memory_limit_mb: cfg.memory_limit_mb,
|
|
kind: cfg.kind,
|
|
sandbox: cfg.sandbox,
|
|
};
|
|
let resp = self
|
|
.request(Method::PUT, &format!("/api/v1/admin/scripts/{id}"))
|
|
.json(&body)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `POST /api/v1/execute/{id}` — returns the raw HTTP status, headers,
|
|
/// and JSON body (the orchestrator marshals the script's output as
|
|
/// the HTTP response itself, not a wrapper object).
|
|
pub async fn execute(
|
|
&self,
|
|
id: &str,
|
|
body: Value,
|
|
headers: &[(String, String)],
|
|
) -> Result<ExecuteResponse> {
|
|
let id = seg(id);
|
|
let mut req = self
|
|
.request(Method::POST, &format!("/api/v1/execute/{id}"))
|
|
.json(&body);
|
|
for (k, v) in headers {
|
|
req = req.header(k, v);
|
|
}
|
|
let resp = req.send().await?;
|
|
let status = resp.status().as_u16();
|
|
let mut headers_out: BTreeMap<String, String> = BTreeMap::new();
|
|
for (k, v) in resp.headers() {
|
|
if let Ok(val) = v.to_str() {
|
|
headers_out.insert(k.as_str().to_string(), val.to_string());
|
|
}
|
|
}
|
|
let bytes = resp.bytes().await.context("reading execute response")?;
|
|
let body_json: Value = if bytes.is_empty() {
|
|
Value::Null
|
|
} else {
|
|
serde_json::from_slice(&bytes)
|
|
.unwrap_or(Value::String(String::from_utf8_lossy(&bytes).into_owned()))
|
|
};
|
|
Ok(ExecuteResponse {
|
|
status_code: status,
|
|
headers: headers_out,
|
|
body: body_json,
|
|
})
|
|
}
|
|
|
|
/// `GET /api/v1/admin/scripts/{id}/logs?limit=N`
|
|
pub async fn logs_list(
|
|
&self,
|
|
script_id: &str,
|
|
limit: u32,
|
|
source: Option<&str>,
|
|
) -> Result<Vec<ExecutionLog>> {
|
|
let script_id = seg(script_id);
|
|
let mut path = format!("/api/v1/admin/scripts/{script_id}/logs?limit={limit}");
|
|
if let Some(src) = source {
|
|
path.push_str("&source=");
|
|
path.push_str(&seg(src));
|
|
}
|
|
let resp = self.request(Method::GET, &path).send().await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `POST /api/v1/admin/auth/logout` — best-effort: server returns
|
|
/// 204 whether or not the token matched a live session, so we just
|
|
/// fire and discard the body. Caller still wipes the local creds.
|
|
pub async fn auth_logout(&self) -> Result<()> {
|
|
let resp = self
|
|
.request(Method::POST, "/api/v1/admin/auth/logout")
|
|
.send()
|
|
.await?;
|
|
decode_status(resp).await
|
|
}
|
|
|
|
/// `GET /api/v1/admin/api-keys` — caller's keys only (server filters
|
|
/// by user_id, no cross-user enumeration).
|
|
pub async fn apikeys_list(&self) -> Result<Vec<ApiKeyDto>> {
|
|
let resp = self
|
|
.request(Method::GET, "/api/v1/admin/api-keys")
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `POST /api/v1/admin/api-keys` — `raw_token` is in the response
|
|
/// **once** and never appears in `GET /api-keys` afterward.
|
|
pub async fn apikeys_mint(&self, body: &MintApiKeyBody<'_>) -> Result<MintApiKeyResponseDto> {
|
|
let resp = self
|
|
.request(Method::POST, "/api/v1/admin/api-keys")
|
|
.json(body)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `DELETE /api/v1/admin/api-keys/{id}` — 404 covers both "doesn't
|
|
/// exist" and "not yours" (server flattens to avoid enumeration).
|
|
pub async fn apikeys_delete(&self, id: &str) -> Result<()> {
|
|
let id = seg(id);
|
|
let resp = self
|
|
.request(Method::DELETE, &format!("/api/v1/admin/api-keys/{id}"))
|
|
.send()
|
|
.await?;
|
|
decode_status(resp).await
|
|
}
|
|
|
|
/// `GET /api/v1/admin/scripts/{id}/routes`
|
|
pub async fn routes_list_for_script(&self, script_id: &str) -> Result<Vec<Route>> {
|
|
let script_id = seg(script_id);
|
|
let resp = self
|
|
.request(
|
|
Method::GET,
|
|
&format!("/api/v1/admin/scripts/{script_id}/routes"),
|
|
)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `POST /api/v1/admin/scripts/{id}/routes`
|
|
pub async fn routes_create(
|
|
&self,
|
|
script_id: &str,
|
|
body: &CreateRouteBody<'_>,
|
|
) -> Result<Route> {
|
|
let script_id = seg(script_id);
|
|
let resp = self
|
|
.request(
|
|
Method::POST,
|
|
&format!("/api/v1/admin/scripts/{script_id}/routes"),
|
|
)
|
|
.json(body)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `DELETE /api/v1/admin/routes/{route_id}`
|
|
pub async fn routes_delete(&self, route_id: &str) -> Result<()> {
|
|
let route_id = seg(route_id);
|
|
let resp = self
|
|
.request(Method::DELETE, &format!("/api/v1/admin/routes/{route_id}"))
|
|
.send()
|
|
.await?;
|
|
decode_status(resp).await
|
|
}
|
|
|
|
/// `POST /api/v1/admin/routes:check` — dry-run conflict check for a
|
|
/// hypothetical route, scoped to one app.
|
|
pub async fn routes_check(&self, body: &CheckRouteBody) -> Result<CheckRouteResponseDto> {
|
|
let resp = self
|
|
.request(Method::POST, "/api/v1/admin/routes:check")
|
|
.json(body)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `POST /api/v1/admin/routes:match` — what route would the given
|
|
/// URL+method match, if any, for the given app.
|
|
pub async fn routes_match(&self, body: &MatchRouteBody<'_>) -> Result<MatchRouteResponseDto> {
|
|
let resp = self
|
|
.request(Method::POST, "/api/v1/admin/routes:match")
|
|
.json(body)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `GET /api/v1/admin/admins`
|
|
pub async fn admins_list(&self) -> Result<Vec<AdminDto>> {
|
|
let resp = self
|
|
.request(Method::GET, "/api/v1/admin/admins")
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `GET /api/v1/admin/admins/{id}`
|
|
pub async fn admins_get(&self, id: &str) -> Result<AdminDto> {
|
|
let id = seg(id);
|
|
let resp = self
|
|
.request(Method::GET, &format!("/api/v1/admin/admins/{id}"))
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `POST /api/v1/admin/admins`
|
|
pub async fn admins_create(&self, body: &CreateAdminBody<'_>) -> Result<AdminDto> {
|
|
let resp = self
|
|
.request(Method::POST, "/api/v1/admin/admins")
|
|
.json(body)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `PATCH /api/v1/admin/admins/{id}`
|
|
pub async fn admins_patch(&self, id: &str, body: &PatchAdminBody<'_>) -> Result<AdminDto> {
|
|
let id = seg(id);
|
|
let resp = self
|
|
.request(Method::PATCH, &format!("/api/v1/admin/admins/{id}"))
|
|
.json(body)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `DELETE /api/v1/admin/admins/{id}`
|
|
pub async fn admins_delete(&self, id: &str) -> Result<()> {
|
|
let id = seg(id);
|
|
let resp = self
|
|
.request(Method::DELETE, &format!("/api/v1/admin/admins/{id}"))
|
|
.send()
|
|
.await?;
|
|
decode_status(resp).await
|
|
}
|
|
|
|
/// `GET /api/v1/admin/apps/{id}/triggers`
|
|
pub async fn triggers_list(&self, app: &str) -> Result<TriggerListDto> {
|
|
let app = seg(app);
|
|
let resp = self
|
|
.request(Method::GET, &format!("/api/v1/admin/apps/{app}/triggers"))
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `DELETE /api/v1/admin/apps/{id}/triggers/{trigger_id}`
|
|
pub async fn triggers_delete(&self, app: &str, trigger_id: &str) -> Result<()> {
|
|
let (app, trigger_id) = (seg(app), seg(trigger_id));
|
|
let resp = self
|
|
.request(
|
|
Method::DELETE,
|
|
&format!("/api/v1/admin/apps/{app}/triggers/{trigger_id}"),
|
|
)
|
|
.send()
|
|
.await?;
|
|
decode_status(resp).await
|
|
}
|
|
|
|
/// `POST /api/v1/admin/apps/{id}/triggers/{kind}` — the body shape
|
|
/// depends on `kind`; the CLI passes a pre-built JSON value so
|
|
/// each create subcommand can construct its own per-kind body.
|
|
pub async fn triggers_create(
|
|
&self,
|
|
app: &str,
|
|
kind: &str,
|
|
body: &serde_json::Value,
|
|
) -> Result<TriggerDto> {
|
|
let (app, kind) = (seg(app), seg(kind));
|
|
let resp = self
|
|
.request(
|
|
Method::POST,
|
|
&format!("/api/v1/admin/apps/{app}/triggers/{kind}"),
|
|
)
|
|
.json(body)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `GET /api/v1/admin/apps/{id}/dead_letters/count`
|
|
pub async fn dead_letters_count(&self, app: &str) -> Result<DeadLetterCountDto> {
|
|
let app = seg(app);
|
|
let resp = self
|
|
.request(
|
|
Method::GET,
|
|
&format!("/api/v1/admin/apps/{app}/dead_letters/count"),
|
|
)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `GET /api/v1/admin/apps/{id}/dead_letters?unresolved={bool}&limit={n}`
|
|
pub async fn dead_letters_list(
|
|
&self,
|
|
app: &str,
|
|
unresolved: bool,
|
|
limit: u32,
|
|
) -> Result<DeadLetterListDto> {
|
|
let app = seg(app);
|
|
let path =
|
|
format!("/api/v1/admin/apps/{app}/dead_letters?unresolved={unresolved}&limit={limit}");
|
|
let resp = self.request(Method::GET, &path).send().await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `GET /api/v1/admin/apps/{id}/dead_letters/{dl_id}`
|
|
pub async fn dead_letters_get(&self, app: &str, dl_id: &str) -> Result<DeadLetterDto> {
|
|
let (app, dl_id) = (seg(app), seg(dl_id));
|
|
let resp = self
|
|
.request(
|
|
Method::GET,
|
|
&format!("/api/v1/admin/apps/{app}/dead_letters/{dl_id}"),
|
|
)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `POST /api/v1/admin/apps/{id}/dead_letters/{dl_id}/replay`
|
|
pub async fn dead_letters_replay(&self, app: &str, dl_id: &str) -> Result<()> {
|
|
let (app, dl_id) = (seg(app), seg(dl_id));
|
|
let resp = self
|
|
.request(
|
|
Method::POST,
|
|
&format!("/api/v1/admin/apps/{app}/dead_letters/{dl_id}/replay"),
|
|
)
|
|
.send()
|
|
.await?;
|
|
decode_status(resp).await
|
|
}
|
|
|
|
/// `POST /api/v1/admin/apps/{id}/dead_letters/{dl_id}/resolve`
|
|
pub async fn dead_letters_resolve(&self, app: &str, dl_id: &str, reason: &str) -> Result<()> {
|
|
let (app, dl_id) = (seg(app), seg(dl_id));
|
|
let resp = self
|
|
.request(
|
|
Method::POST,
|
|
&format!("/api/v1/admin/apps/{app}/dead_letters/{dl_id}/resolve"),
|
|
)
|
|
.json(&serde_json::json!({ "reason": reason }))
|
|
.send()
|
|
.await?;
|
|
decode_status(resp).await
|
|
}
|
|
|
|
/// `GET /api/v1/admin/{apps,groups}/{id}/secrets` — secret names +
|
|
/// last-modified for the owner. Values never travel on this path. `env`
|
|
/// is only meaningful for group owners (app secrets are env-agnostic).
|
|
pub async fn secrets_list(
|
|
&self,
|
|
owner: VarOwnerArg<'_>,
|
|
env: Option<&str>,
|
|
) -> Result<SecretListDto> {
|
|
let mut path = format!("{}/secrets", owner.base_path());
|
|
if let Some(env) = env {
|
|
path.push_str(&format!("?env={}", seg(env)));
|
|
}
|
|
let resp = self.request(Method::GET, &path).send().await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `POST /api/v1/admin/{apps,groups}/{id}/secrets`. `env` rides in the
|
|
/// body and is only honored by group owners.
|
|
pub async fn secrets_set(
|
|
&self,
|
|
owner: VarOwnerArg<'_>,
|
|
name: &str,
|
|
value: serde_json::Value,
|
|
env: Option<&str>,
|
|
) -> Result<()> {
|
|
// `name` travels in the JSON body, not the path.
|
|
let mut body = serde_json::json!({ "name": name, "value": value });
|
|
if let Some(env) = env {
|
|
body["env"] = serde_json::Value::String(env.to_string());
|
|
}
|
|
let resp = self
|
|
.request(Method::POST, &format!("{}/secrets", owner.base_path()))
|
|
.json(&body)
|
|
.send()
|
|
.await?;
|
|
decode_status(resp).await
|
|
}
|
|
|
|
/// `DELETE /api/v1/admin/{apps,groups}/{id}/secrets/{name}`
|
|
pub async fn secrets_delete(
|
|
&self,
|
|
owner: VarOwnerArg<'_>,
|
|
name: &str,
|
|
env: Option<&str>,
|
|
) -> Result<()> {
|
|
let mut path = format!("{}/secrets/{}", owner.base_path(), seg(name));
|
|
if let Some(env) = env {
|
|
path.push_str(&format!("?env={}", seg(env)));
|
|
}
|
|
let resp = self.request(Method::DELETE, &path).send().await?;
|
|
decode_status(resp).await
|
|
}
|
|
|
|
/// `GET /api/v1/admin/groups/{id}/secrets/{name}/value` — the ONLY path
|
|
/// that returns a decrypted secret value. Gated server-side at the owning
|
|
/// group; there is no app-secret equivalent by design.
|
|
pub async fn group_secret_read_value(
|
|
&self,
|
|
group: &str,
|
|
name: &str,
|
|
env: Option<&str>,
|
|
) -> Result<SecretValueDto> {
|
|
let (group, name) = (seg(group), seg(name));
|
|
let mut path = format!("/api/v1/admin/groups/{group}/secrets/{name}/value");
|
|
if let Some(env) = env {
|
|
path.push_str(&format!("?env={}", seg(env)));
|
|
}
|
|
let resp = self.request(Method::GET, &path).send().await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
// ---------- vars (Phase 3 config) ----------
|
|
|
|
/// `GET /api/v1/admin/{apps,groups}/{id}/vars` — the owner's OWN vars
|
|
/// (not the resolved/inherited view).
|
|
pub async fn vars_list(&self, owner: VarOwnerArg<'_>) -> Result<VarListDto> {
|
|
let resp = self
|
|
.request(Method::GET, &format!("{}/vars", owner.base_path()))
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `PUT /api/v1/admin/{apps,groups}/{id}/vars`
|
|
pub async fn vars_set(
|
|
&self,
|
|
owner: VarOwnerArg<'_>,
|
|
key: &str,
|
|
value: serde_json::Value,
|
|
env: Option<&str>,
|
|
tombstone: bool,
|
|
) -> Result<()> {
|
|
let mut body = serde_json::json!({ "key": key, "value": value, "tombstone": tombstone });
|
|
if let Some(env) = env {
|
|
body["env"] = serde_json::Value::String(env.to_string());
|
|
}
|
|
let resp = self
|
|
.request(Method::PUT, &format!("{}/vars", owner.base_path()))
|
|
.json(&body)
|
|
.send()
|
|
.await?;
|
|
decode_status(resp).await
|
|
}
|
|
|
|
/// `DELETE /api/v1/admin/{apps,groups}/{id}/vars/{key}`
|
|
pub async fn vars_delete(
|
|
&self,
|
|
owner: VarOwnerArg<'_>,
|
|
key: &str,
|
|
env: Option<&str>,
|
|
) -> Result<()> {
|
|
let mut path = format!("{}/vars/{}", owner.base_path(), seg(key));
|
|
if let Some(env) = env {
|
|
path.push_str(&format!("?env={}", seg(env)));
|
|
}
|
|
let resp = self.request(Method::DELETE, &path).send().await?;
|
|
decode_status(resp).await
|
|
}
|
|
|
|
/// `GET /api/v1/admin/apps/{id}/config/effective` — the app's resolved
|
|
/// (group-inherited) vars plus masked secret statuses, each annotated with
|
|
/// the owner that won and the layers it merged from (§4.6).
|
|
pub async fn config_effective(&self, app: &str) -> Result<EffectiveConfigDto> {
|
|
let app = seg(app);
|
|
let resp = self
|
|
.request(
|
|
Method::GET,
|
|
&format!("/api/v1/admin/apps/{app}/config/effective"),
|
|
)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
// ---------- domains ----------
|
|
|
|
/// `GET /api/v1/admin/apps/{id_or_slug}/domains`
|
|
pub async fn domains_list(&self, app: &str) -> Result<Vec<AppDomain>> {
|
|
let app = seg(app);
|
|
let resp = self
|
|
.request(Method::GET, &format!("/api/v1/admin/apps/{app}/domains"))
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `POST /api/v1/admin/apps/{id_or_slug}/domains`
|
|
pub async fn domains_create(&self, app: &str, pattern: &str) -> Result<AppDomain> {
|
|
let app = seg(app);
|
|
let resp = self
|
|
.request(Method::POST, &format!("/api/v1/admin/apps/{app}/domains"))
|
|
.json(&serde_json::json!({ "pattern": pattern }))
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `DELETE /api/v1/admin/apps/{id_or_slug}/domains/{domain_id}`
|
|
pub async fn domains_delete(&self, app: &str, domain_id: &str) -> Result<()> {
|
|
let (app, domain_id) = (seg(app), seg(domain_id));
|
|
let resp = self
|
|
.request(
|
|
Method::DELETE,
|
|
&format!("/api/v1/admin/apps/{app}/domains/{domain_id}"),
|
|
)
|
|
.send()
|
|
.await?;
|
|
decode_status(resp).await
|
|
}
|
|
|
|
// ---------- topics ----------
|
|
|
|
/// `GET /api/v1/admin/apps/{id_or_slug}/topics`
|
|
pub async fn topics_list(&self, app: &str) -> Result<Vec<TopicDto>> {
|
|
let app = seg(app);
|
|
let resp = self
|
|
.request(Method::GET, &format!("/api/v1/admin/apps/{app}/topics"))
|
|
.send()
|
|
.await?;
|
|
let body: TopicListDto = decode(resp).await?;
|
|
Ok(body.topics)
|
|
}
|
|
|
|
/// `POST /api/v1/admin/apps/{id_or_slug}/topics`
|
|
pub async fn topics_create(
|
|
&self,
|
|
app: &str,
|
|
name: &str,
|
|
external_subscribable: bool,
|
|
auth_mode: &str,
|
|
) -> Result<TopicDto> {
|
|
let app = seg(app);
|
|
let resp = self
|
|
.request(Method::POST, &format!("/api/v1/admin/apps/{app}/topics"))
|
|
.json(&serde_json::json!({
|
|
"name": name,
|
|
"external_subscribable": external_subscribable,
|
|
"auth_mode": auth_mode,
|
|
}))
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `PATCH /api/v1/admin/apps/{id_or_slug}/topics/{name}` — only the
|
|
/// fields the caller set are sent; the server leaves the rest alone.
|
|
pub async fn topics_update(
|
|
&self,
|
|
app: &str,
|
|
name: &str,
|
|
external_subscribable: Option<bool>,
|
|
auth_mode: Option<&str>,
|
|
) -> Result<TopicDto> {
|
|
let mut body = serde_json::Map::new();
|
|
if let Some(e) = external_subscribable {
|
|
body.insert("external_subscribable".into(), Value::Bool(e));
|
|
}
|
|
if let Some(m) = auth_mode {
|
|
body.insert("auth_mode".into(), Value::String(m.to_string()));
|
|
}
|
|
let (app, name) = (seg(app), seg(name));
|
|
let resp = self
|
|
.request(
|
|
Method::PATCH,
|
|
&format!("/api/v1/admin/apps/{app}/topics/{name}"),
|
|
)
|
|
.json(&Value::Object(body))
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `DELETE /api/v1/admin/apps/{id_or_slug}/topics/{name}`
|
|
pub async fn topics_delete(&self, app: &str, name: &str) -> Result<()> {
|
|
let (app, name) = (seg(app), seg(name));
|
|
let resp = self
|
|
.request(
|
|
Method::DELETE,
|
|
&format!("/api/v1/admin/apps/{app}/topics/{name}"),
|
|
)
|
|
.send()
|
|
.await?;
|
|
decode_status(resp).await
|
|
}
|
|
|
|
// ---------- app end-users ----------
|
|
|
|
/// `GET /api/v1/admin/apps/{id_or_slug}/users?limit={n}`
|
|
pub async fn app_users_list(&self, app: &str, limit: u32) -> Result<Vec<AppUser>> {
|
|
let app = seg(app);
|
|
let resp = self
|
|
.request(
|
|
Method::GET,
|
|
&format!("/api/v1/admin/apps/{app}/users?limit={limit}"),
|
|
)
|
|
.send()
|
|
.await?;
|
|
let body: ListUsersResponseDto = decode(resp).await?;
|
|
Ok(body.users)
|
|
}
|
|
|
|
/// `GET /api/v1/admin/apps/{id_or_slug}/users/{user_id}`
|
|
pub async fn app_user_get(&self, app: &str, user_id: &str) -> Result<AppUser> {
|
|
let (app, user_id) = (seg(app), seg(user_id));
|
|
let resp = self
|
|
.request(
|
|
Method::GET,
|
|
&format!("/api/v1/admin/apps/{app}/users/{user_id}"),
|
|
)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `POST /api/v1/admin/apps/{id_or_slug}/users/{user_id}/reset-password`
|
|
pub async fn app_user_reset_password(
|
|
&self,
|
|
app: &str,
|
|
user_id: &str,
|
|
) -> Result<ResetPasswordResponseDto> {
|
|
let (app, user_id) = (seg(app), seg(user_id));
|
|
let resp = self
|
|
.request(
|
|
Method::POST,
|
|
&format!("/api/v1/admin/apps/{app}/users/{user_id}/reset-password"),
|
|
)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `POST /api/v1/admin/apps/{id_or_slug}/users/{user_id}/revoke-sessions`
|
|
pub async fn app_user_revoke_sessions(
|
|
&self,
|
|
app: &str,
|
|
user_id: &str,
|
|
) -> Result<RevokeSessionsResponseDto> {
|
|
let (app, user_id) = (seg(app), seg(user_id));
|
|
let resp = self
|
|
.request(
|
|
Method::POST,
|
|
&format!("/api/v1/admin/apps/{app}/users/{user_id}/revoke-sessions"),
|
|
)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
// --- App membership (G2) ----------------------------------------------
|
|
|
|
/// `GET /api/v1/admin/apps/{id_or_slug}/members`
|
|
pub async fn members_list(&self, app: &str) -> Result<Vec<AppMemberDto>> {
|
|
let app = seg(app);
|
|
let resp = self
|
|
.request(Method::GET, &format!("/api/v1/admin/apps/{app}/members"))
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `POST /api/v1/admin/apps/{id_or_slug}/members`
|
|
pub async fn members_grant(
|
|
&self,
|
|
app: &str,
|
|
user_id: &str,
|
|
role: AppRole,
|
|
) -> Result<AppMemberDto> {
|
|
let app = seg(app);
|
|
let body = serde_json::json!({ "user_id": user_id, "role": role });
|
|
let resp = self
|
|
.request(Method::POST, &format!("/api/v1/admin/apps/{app}/members"))
|
|
.json(&body)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `PATCH /api/v1/admin/apps/{id_or_slug}/members/{user_id}`
|
|
pub async fn members_set_role(
|
|
&self,
|
|
app: &str,
|
|
user_id: &str,
|
|
role: AppRole,
|
|
) -> Result<AppMemberDto> {
|
|
let (app, user_id) = (seg(app), seg(user_id));
|
|
let body = serde_json::json!({ "role": role });
|
|
let resp = self
|
|
.request(
|
|
Method::PATCH,
|
|
&format!("/api/v1/admin/apps/{app}/members/{user_id}"),
|
|
)
|
|
.json(&body)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `DELETE /api/v1/admin/apps/{id_or_slug}/members/{user_id}`
|
|
pub async fn members_remove(&self, app: &str, user_id: &str) -> Result<()> {
|
|
let (app, user_id) = (seg(app), seg(user_id));
|
|
let resp = self
|
|
.request(
|
|
Method::DELETE,
|
|
&format!("/api/v1/admin/apps/{app}/members/{user_id}"),
|
|
)
|
|
.send()
|
|
.await?;
|
|
decode_status(resp).await
|
|
}
|
|
|
|
// --- Files (G2, read-only admin surface) ------------------------------
|
|
|
|
/// `GET /api/v1/admin/apps/{id_or_slug}/files?collection=&limit=`
|
|
pub async fn files_list(
|
|
&self,
|
|
app: &str,
|
|
collection: &str,
|
|
limit: u32,
|
|
) -> Result<ListFilesResponse> {
|
|
let app = seg(app);
|
|
let collection = seg(collection);
|
|
let resp = self
|
|
.request(
|
|
Method::GET,
|
|
&format!("/api/v1/admin/apps/{app}/files?collection={collection}&limit={limit}"),
|
|
)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `GET /api/v1/admin/apps/{id_or_slug}/files/{collection}/{file_id}` —
|
|
/// streams the raw bytes (download). Returns the body verbatim.
|
|
pub async fn files_get_bytes(
|
|
&self,
|
|
app: &str,
|
|
collection: &str,
|
|
file_id: &str,
|
|
) -> Result<Vec<u8>> {
|
|
let (app, collection, file_id) = (seg(app), seg(collection), seg(file_id));
|
|
let resp = self
|
|
.request(
|
|
Method::GET,
|
|
&format!("/api/v1/admin/apps/{app}/files/{collection}/{file_id}"),
|
|
)
|
|
.send()
|
|
.await?;
|
|
if resp.status().is_success() {
|
|
Ok(resp.bytes().await.context("reading file bytes")?.to_vec())
|
|
} else {
|
|
Err(server_error(resp).await)
|
|
}
|
|
}
|
|
|
|
/// `DELETE /api/v1/admin/apps/{id_or_slug}/files/{collection}/{file_id}`
|
|
pub async fn files_delete(&self, app: &str, collection: &str, file_id: &str) -> Result<()> {
|
|
let (app, collection, file_id) = (seg(app), seg(collection), seg(file_id));
|
|
let resp = self
|
|
.request(
|
|
Method::DELETE,
|
|
&format!("/api/v1/admin/apps/{app}/files/{collection}/{file_id}"),
|
|
)
|
|
.send()
|
|
.await?;
|
|
decode_status(resp).await
|
|
}
|
|
|
|
// --- KV (G2, read-only admin surface) ---------------------------------
|
|
|
|
/// `GET /api/v1/admin/apps/{id_or_slug}/kv?collection=&limit=`
|
|
pub async fn kv_list(&self, app: &str, collection: &str, limit: u32) -> Result<KvListPageDto> {
|
|
let app = seg(app);
|
|
let collection = seg(collection);
|
|
let resp = self
|
|
.request(
|
|
Method::GET,
|
|
&format!("/api/v1/admin/apps/{app}/kv?collection={collection}&limit={limit}"),
|
|
)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `GET /api/v1/admin/apps/{id_or_slug}/kv/{collection}/{key}`
|
|
pub async fn kv_get(&self, app: &str, collection: &str, key: &str) -> Result<Value> {
|
|
let (app, collection, key) = (seg(app), seg(collection), seg(key));
|
|
let resp = self
|
|
.request(
|
|
Method::GET,
|
|
&format!("/api/v1/admin/apps/{app}/kv/{collection}/{key}"),
|
|
)
|
|
.send()
|
|
.await?;
|
|
let wrapped: KvGetResponse = decode(resp).await?;
|
|
Ok(wrapped.value)
|
|
}
|
|
|
|
// --- Queues (G2, read-only admin surface) -----------------------------
|
|
|
|
/// `GET /api/v1/admin/apps/{id_or_slug}/queues`
|
|
pub async fn queues_list(&self, app: &str) -> Result<Vec<QueueSummaryDto>> {
|
|
let app = seg(app);
|
|
let resp = self
|
|
.request(Method::GET, &format!("/api/v1/admin/apps/{app}/queues"))
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `GET /api/v1/admin/apps/{id_or_slug}/queues/{queue_name}`
|
|
pub async fn queue_get(&self, app: &str, queue_name: &str) -> Result<QueueDetailDto> {
|
|
let (app, queue_name) = (seg(app), seg(queue_name));
|
|
let resp = self
|
|
.request(
|
|
Method::GET,
|
|
&format!("/api/v1/admin/apps/{app}/queues/{queue_name}"),
|
|
)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `POST /api/v1/admin/apps/{id_or_slug}/plan` — diff a desired-state
|
|
/// bundle against the app's live state. Read-only.
|
|
pub async fn plan(&self, app: &str, bundle: &serde_json::Value) -> Result<PlanDto> {
|
|
let app = seg(app);
|
|
let resp = self
|
|
.request(Method::POST, &format!("/api/v1/admin/apps/{app}/plan"))
|
|
.json(bundle)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
/// `POST /api/v1/admin/apps/{id_or_slug}/apply` — reconcile the live
|
|
/// app to the bundle in one transaction.
|
|
pub async fn apply(
|
|
&self,
|
|
app: &str,
|
|
bundle: &serde_json::Value,
|
|
prune: bool,
|
|
expected_token: Option<&str>,
|
|
) -> Result<ApplyReportDto> {
|
|
let app = seg(app);
|
|
let body = serde_json::json!({
|
|
"bundle": bundle,
|
|
"prune": prune,
|
|
"expected_token": expected_token,
|
|
});
|
|
let resp = self
|
|
.request(Method::POST, &format!("/api/v1/admin/apps/{app}/apply"))
|
|
.json(&body)
|
|
.send()
|
|
.await?;
|
|
// The apply endpoint returns 409 only for a stale bound plan
|
|
// (`StateMoved`): the app changed since `pic plan` recorded its
|
|
// token. Surface an actionable next step instead of a bare
|
|
// `HTTP 409`.
|
|
if resp.status() == reqwest::StatusCode::CONFLICT {
|
|
let body = resp.text().await.unwrap_or_default();
|
|
let msg = parse_error_body(&body).unwrap_or(body);
|
|
return Err(anyhow!(
|
|
"{msg}\nThe app changed since your last `pic plan`. Re-run \
|
|
`pic plan` to review the new diff, then `pic apply` — or \
|
|
`pic apply --force` to apply without re-reviewing."
|
|
));
|
|
}
|
|
decode(resp).await
|
|
}
|
|
}
|
|
|
|
/// `POST /api/v1/admin/auth/login` — sits outside the `Client` because
|
|
/// it runs before any token exists. Mirrors the dashboard's login.ts
|
|
/// wire shape (see `manager-core/src/auth_api.rs:49-60`).
|
|
pub async fn auth_login(url: &str, username: &str, password: &str) -> Result<LoginResponseDto> {
|
|
let http = reqwest::Client::builder()
|
|
.user_agent(concat!("pic/", env!("CARGO_PKG_VERSION")))
|
|
.build()
|
|
.context("building HTTP client")?;
|
|
let body = LoginRequestBody { username, password };
|
|
let resp = http
|
|
.post(format!(
|
|
"{}/api/v1/admin/auth/login",
|
|
url.trim_end_matches('/')
|
|
))
|
|
.json(&body)
|
|
.send()
|
|
.await?;
|
|
decode(resp).await
|
|
}
|
|
|
|
// ---------- DTOs (CLI-local, wire-shape-matched) ----------
|
|
|
|
/// Response of `POST .../plan`: per-resource diffs grouped by kind.
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct PlanDto {
|
|
#[serde(default)]
|
|
pub scripts: Vec<ChangeDto>,
|
|
#[serde(default)]
|
|
pub routes: Vec<ChangeDto>,
|
|
#[serde(default)]
|
|
pub triggers: Vec<ChangeDto>,
|
|
#[serde(default)]
|
|
pub secrets: Vec<ChangeDto>,
|
|
#[serde(default)]
|
|
pub vars: Vec<ChangeDto>,
|
|
/// Fingerprint of the live state this plan was computed against; carried
|
|
/// in `.picloud/` and replayed to `apply` for the bound-plan check.
|
|
#[serde(default)]
|
|
pub state_token: String,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct ChangeDto {
|
|
pub op: String,
|
|
pub key: String,
|
|
#[serde(default)]
|
|
pub detail: Option<String>,
|
|
}
|
|
|
|
/// Response of `POST .../apply`: counts of what changed.
|
|
#[derive(Debug, Default, Deserialize)]
|
|
pub struct ApplyReportDto {
|
|
#[serde(default)]
|
|
pub scripts_created: u32,
|
|
#[serde(default)]
|
|
pub scripts_updated: u32,
|
|
#[serde(default)]
|
|
pub scripts_deleted: u32,
|
|
#[serde(default)]
|
|
pub routes_created: u32,
|
|
#[serde(default)]
|
|
pub routes_updated: u32,
|
|
#[serde(default)]
|
|
pub routes_deleted: u32,
|
|
#[serde(default)]
|
|
pub triggers_created: u32,
|
|
#[serde(default)]
|
|
pub triggers_deleted: u32,
|
|
#[serde(default)]
|
|
pub vars_created: u32,
|
|
#[serde(default)]
|
|
pub vars_updated: u32,
|
|
#[serde(default)]
|
|
pub vars_deleted: u32,
|
|
#[serde(default)]
|
|
pub warnings: Vec<String>,
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct AuthMeDto {
|
|
// Part of the wire shape (and kept for symmetry with the dashboard's
|
|
// MeDto), even though the CLI never displays it.
|
|
pub id: String,
|
|
pub username: String,
|
|
pub instance_role: InstanceRole,
|
|
#[serde(default)]
|
|
pub email: Option<String>,
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct AppLookupDto {
|
|
#[serde(flatten)]
|
|
pub app: App,
|
|
// Not surfaced yet — `pic apps ls` only shows what `apps_list` returns.
|
|
// Kept on the DTO so future `pic apps inspect <slug>` work is one-line.
|
|
#[serde(default)]
|
|
pub my_role: Option<AppRole>,
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct CreateAppBody<'a> {
|
|
pub slug: &'a str,
|
|
pub name: &'a str,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub description: Option<&'a str>,
|
|
/// Parent group (slug or id); omit for the instance root.
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub group: Option<&'a str>,
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct CreateGroupBody<'a> {
|
|
pub slug: &'a str,
|
|
pub name: &'a str,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub description: Option<&'a str>,
|
|
/// Parent group (slug or id); omit for a root-level group.
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub parent: Option<&'a str>,
|
|
}
|
|
|
|
/// `GET /groups/{id}` response — the group plus its breadcrumb path and
|
|
/// direct children.
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct GroupDetailDto {
|
|
#[serde(flatten)]
|
|
pub group: Group,
|
|
pub path: Vec<Group>,
|
|
pub subgroups: Vec<Group>,
|
|
pub apps: Vec<App>,
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct CreateRouteBody<'a> {
|
|
pub host_kind: HostKind,
|
|
#[serde(skip_serializing_if = "str::is_empty")]
|
|
pub host: &'a str,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub host_param_name: Option<&'a str>,
|
|
pub path_kind: PathKind,
|
|
pub path: &'a str,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub method: Option<&'a str>,
|
|
pub dispatch_mode: DispatchMode,
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct CheckRouteBody {
|
|
pub app_id: AppId,
|
|
pub host_kind: HostKind,
|
|
#[serde(skip_serializing_if = "String::is_empty")]
|
|
pub host: String,
|
|
pub path_kind: PathKind,
|
|
pub path: String,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub method: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct CheckRouteResponseDto {
|
|
pub ok: bool,
|
|
#[serde(default)]
|
|
pub conflicting_route: Option<Route>,
|
|
#[serde(default)]
|
|
pub conflict_reason: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct MatchRouteBody<'a> {
|
|
pub app_id: AppId,
|
|
pub url: &'a str,
|
|
pub method: &'a str,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct MatchRouteResponseDto {
|
|
#[serde(default)]
|
|
pub matched: Option<MatchedRouteDto>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct MatchedRouteDto {
|
|
pub route_id: String,
|
|
pub script_id: ScriptId,
|
|
#[serde(default)]
|
|
pub params: BTreeMap<String, String>,
|
|
#[serde(default)]
|
|
pub rest: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct CreateAdminBody<'a> {
|
|
pub username: &'a str,
|
|
pub password: &'a str,
|
|
pub instance_role: InstanceRole,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub email: Option<&'a str>,
|
|
}
|
|
|
|
#[derive(Debug, Default, Serialize)]
|
|
pub struct PatchAdminBody<'a> {
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub username: Option<&'a str>,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub password: Option<&'a str>,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub is_active: Option<bool>,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub instance_role: Option<InstanceRole>,
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct AdminDto {
|
|
pub id: AdminUserId,
|
|
pub username: String,
|
|
pub is_active: bool,
|
|
pub instance_role: InstanceRole,
|
|
#[serde(default)]
|
|
pub email: Option<String>,
|
|
pub created_at: DateTime<Utc>,
|
|
#[serde(default)]
|
|
pub last_login_at: Option<DateTime<Utc>>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct TriggerListDto {
|
|
pub triggers: Vec<TriggerDto>,
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct TriggerDto {
|
|
pub id: String,
|
|
pub app_id: AppId,
|
|
pub script_id: ScriptId,
|
|
pub kind: String,
|
|
pub enabled: bool,
|
|
pub dispatch_mode: String,
|
|
pub retry_max_attempts: u32,
|
|
pub created_at: DateTime<Utc>,
|
|
#[serde(default)]
|
|
pub details: Value,
|
|
}
|
|
|
|
/// Topic registry row. The server's `Topic` derives only `Serialize`,
|
|
/// so the CLI carries its own `Deserialize` mirror (same wire shape).
|
|
#[allow(dead_code)]
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct TopicDto {
|
|
pub name: String,
|
|
pub external_subscribable: bool,
|
|
/// `public` | `token` | `session`.
|
|
pub auth_mode: String,
|
|
pub created_at: DateTime<Utc>,
|
|
pub updated_at: DateTime<Utc>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
struct TopicListDto {
|
|
topics: Vec<TopicDto>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
struct ListUsersResponseDto {
|
|
users: Vec<AppUser>,
|
|
// `next_cursor` exists on the wire but the CLI's `ls` is single-page
|
|
// (--limit); pagination is a follow-up.
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct ResetPasswordResponseDto {
|
|
pub token: String,
|
|
pub expires_in_seconds: i64,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct RevokeSessionsResponseDto {
|
|
pub revoked: u64,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct DeadLetterCountDto {
|
|
pub unresolved: i64,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct DeadLetterListDto {
|
|
pub dead_letters: Vec<DeadLetterDto>,
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct DeadLetterDto {
|
|
pub id: String,
|
|
pub app_id: AppId,
|
|
pub source: String,
|
|
pub op: String,
|
|
pub trigger_id: Option<String>,
|
|
pub script_id: Option<ScriptId>,
|
|
pub payload: Value,
|
|
pub attempt_count: u32,
|
|
pub first_attempt_at: DateTime<Utc>,
|
|
pub last_attempt_at: DateTime<Utc>,
|
|
pub last_error: String,
|
|
pub created_at: DateTime<Utc>,
|
|
pub resolved_at: Option<DateTime<Utc>>,
|
|
pub resolution: Option<String>,
|
|
}
|
|
|
|
/// Which owner a `pic vars` call targets. Selects the `apps` vs `groups`
|
|
/// admin path prefix; the identifier travels in the path (encoded).
|
|
#[derive(Debug, Clone, Copy)]
|
|
pub enum VarOwnerArg<'a> {
|
|
App(&'a str),
|
|
Group(&'a str),
|
|
}
|
|
|
|
impl VarOwnerArg<'_> {
|
|
fn base_path(&self) -> String {
|
|
match self {
|
|
Self::App(ident) => format!("/api/v1/admin/apps/{}", seg(ident)),
|
|
Self::Group(ident) => format!("/api/v1/admin/groups/{}", seg(ident)),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct VarListDto {
|
|
pub vars: Vec<VarItemDto>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct VarItemDto {
|
|
pub key: String,
|
|
pub env: String,
|
|
pub value: serde_json::Value,
|
|
pub is_tombstone: bool,
|
|
pub updated_at: DateTime<Utc>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct SecretListDto {
|
|
pub secrets: Vec<SecretItemDto>,
|
|
#[serde(default)]
|
|
#[allow(dead_code)]
|
|
pub next_cursor: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct SecretItemDto {
|
|
pub name: String,
|
|
/// Env scope. Only meaningful (and populated) for group owners; the server
|
|
/// omits it for app secrets, so default to `*` when absent.
|
|
#[serde(default = "default_env")]
|
|
pub env: String,
|
|
pub updated_at: DateTime<Utc>,
|
|
}
|
|
|
|
fn default_env() -> String {
|
|
"*".to_string()
|
|
}
|
|
|
|
/// Plaintext value of a single group secret — the response of the gated
|
|
/// `.../secrets/{name}/value` read. The decrypted value is arbitrary JSON.
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct SecretValueDto {
|
|
#[allow(dead_code)]
|
|
pub name: String,
|
|
#[allow(dead_code)]
|
|
pub env: String,
|
|
pub value: serde_json::Value,
|
|
}
|
|
|
|
// --- effective config (`/config/effective`) ---
|
|
|
|
/// The owner (app or group) a resolved layer belongs to, with its distance
|
|
/// from the app in the inheritance chain (`depth` 0 = the app itself).
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct EffectiveOwnerDto {
|
|
pub kind: String,
|
|
#[allow(dead_code)]
|
|
pub id: String,
|
|
pub depth: u32,
|
|
}
|
|
|
|
/// One layer a resolved var merged from, deepest-first as the server returns it.
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct MergedFromDto {
|
|
pub depth: u32,
|
|
pub scope: String,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct EffectiveVarDto {
|
|
pub value: serde_json::Value,
|
|
pub owner: EffectiveOwnerDto,
|
|
pub scope: String,
|
|
#[serde(default)]
|
|
pub merged_from: Vec<MergedFromDto>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct EffectiveSecretDto {
|
|
#[allow(dead_code)]
|
|
pub status: String,
|
|
pub owner: EffectiveOwnerDto,
|
|
pub scope: String,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct EffectiveConfigDto {
|
|
#[serde(default)]
|
|
pub vars: std::collections::BTreeMap<String, EffectiveVarDto>,
|
|
#[serde(default)]
|
|
pub secrets: std::collections::BTreeMap<String, EffectiveSecretDto>,
|
|
}
|
|
|
|
/// Per-script runtime config the CLI can now set (G3). All optional — an
|
|
/// unset field is omitted so the server applies its own default (and the
|
|
/// `PICLOUD_SANDBOX_MAX_*` admin ceilings still clamp overrides).
|
|
#[derive(Debug, Default, Clone)]
|
|
pub struct ScriptConfig {
|
|
pub timeout_seconds: Option<i32>,
|
|
pub memory_limit_mb: Option<i32>,
|
|
pub kind: Option<ScriptKind>,
|
|
pub sandbox: Option<ScriptSandbox>,
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct CreateScriptBody<'a> {
|
|
pub app_id: AppId,
|
|
pub name: &'a str,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub description: Option<&'a str>,
|
|
pub source: &'a str,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub timeout_seconds: Option<i32>,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub memory_limit_mb: Option<i32>,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub kind: Option<ScriptKind>,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub sandbox: Option<ScriptSandbox>,
|
|
}
|
|
|
|
/// Phase 4: body for `POST /groups/{id}/scripts`. Like `CreateScriptBody`
|
|
/// minus `app_id` — the owning group comes from the path.
|
|
#[derive(Debug, Serialize)]
|
|
pub struct CreateGroupScriptBody<'a> {
|
|
pub name: &'a str,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub description: Option<&'a str>,
|
|
pub source: &'a str,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub timeout_seconds: Option<i32>,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub memory_limit_mb: Option<i32>,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub kind: Option<ScriptKind>,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub sandbox: Option<ScriptSandbox>,
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
struct UpdateScriptBody<'a> {
|
|
source: &'a str,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
timeout_seconds: Option<i32>,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
memory_limit_mb: Option<i32>,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
kind: Option<ScriptKind>,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
sandbox: Option<ScriptSandbox>,
|
|
}
|
|
|
|
// --- G2 response DTOs (deserialize-only mirrors of the server shapes) ---
|
|
|
|
// `#[allow(dead_code)]` on a couple of fields below: these structs mirror
|
|
// the full server response shape (so the surface is documented and future
|
|
// columns are a one-line add), but the TSV/KvBlock renderers don't print
|
|
// every field today.
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct AppMemberDto {
|
|
pub user_id: AdminUserId,
|
|
pub username: String,
|
|
#[allow(dead_code)]
|
|
pub email: Option<String>,
|
|
pub instance_role: InstanceRole,
|
|
pub is_active: bool,
|
|
pub role: AppRole,
|
|
pub created_at: DateTime<Utc>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct FileMetaDto {
|
|
pub id: String,
|
|
#[allow(dead_code)]
|
|
pub collection: String,
|
|
pub name: String,
|
|
pub content_type: String,
|
|
pub size: u64,
|
|
#[allow(dead_code)]
|
|
pub checksum: String,
|
|
#[allow(dead_code)]
|
|
pub created_at: String,
|
|
pub updated_at: String,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct ListFilesResponse {
|
|
pub files: Vec<FileMetaDto>,
|
|
pub next_cursor: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct KvListPageDto {
|
|
pub keys: Vec<String>,
|
|
pub next_cursor: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
struct KvGetResponse {
|
|
value: Value,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct QueueSummaryDto {
|
|
pub queue_name: String,
|
|
pub total: u64,
|
|
pub pending: u64,
|
|
pub claimed: u64,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct QueueConsumerDto {
|
|
pub trigger_id: String,
|
|
pub script_id: ScriptId,
|
|
pub script_name: String,
|
|
pub visibility_timeout_secs: u32,
|
|
pub last_fired_at: Option<DateTime<Utc>>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct QueueDetailDto {
|
|
pub queue_name: String,
|
|
pub total: u64,
|
|
pub pending: u64,
|
|
pub claimed: u64,
|
|
pub consumer: Option<QueueConsumerDto>,
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
struct LoginRequestBody<'a> {
|
|
username: &'a str,
|
|
password: &'a str,
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct LoginResponseDto {
|
|
pub user: LoginUserDto,
|
|
pub token: String,
|
|
pub expires_at: DateTime<Utc>,
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct LoginUserDto {
|
|
pub id: AdminUserId,
|
|
pub username: String,
|
|
pub instance_role: InstanceRole,
|
|
#[serde(default)]
|
|
pub email: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct MintApiKeyBody<'a> {
|
|
pub name: &'a str,
|
|
pub scopes: &'a [Scope],
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub app_id: Option<AppId>,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub expires_at: Option<DateTime<Utc>>,
|
|
}
|
|
|
|
/// Fresh-mint response. The `raw_token` field is the one and only
|
|
/// chance to capture the bearer string; subsequent `GET /api-keys`
|
|
/// returns the `ApiKeyDto` portion without it.
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct MintApiKeyResponseDto {
|
|
#[serde(flatten)]
|
|
pub key: ApiKeyDto,
|
|
pub raw_token: String,
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct ApiKeyDto {
|
|
pub id: ApiKeyId,
|
|
pub prefix: String,
|
|
pub name: String,
|
|
pub scopes: Vec<Scope>,
|
|
pub app_id: Option<AppId>,
|
|
pub expires_at: Option<DateTime<Utc>>,
|
|
pub last_used_at: Option<DateTime<Utc>>,
|
|
pub created_at: DateTime<Utc>,
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
#[derive(Debug)]
|
|
pub struct ExecuteResponse {
|
|
pub status_code: u16,
|
|
// Captured for completeness; not displayed today, but `pic invoke -v`
|
|
// could surface them later without changing this struct.
|
|
pub headers: BTreeMap<String, String>,
|
|
pub body: Value,
|
|
}
|
|
|
|
// ---------- helpers ----------
|
|
|
|
/// Parse `-H "Key: value"` or `-H "Key=value"` into a `(name, value)`
|
|
/// pair. Trims surrounding whitespace on both sides.
|
|
pub fn parse_kv_header(raw: &str) -> Result<(String, String), String> {
|
|
let (k, v) = raw
|
|
.split_once(':')
|
|
.or_else(|| raw.split_once('='))
|
|
.ok_or_else(|| format!("expected `Key: value` or `Key=value`, got {raw:?}"))?;
|
|
let k = k.trim();
|
|
let v = v.trim();
|
|
if k.is_empty() {
|
|
return Err(format!("empty header name in {raw:?}"));
|
|
}
|
|
Ok((k.to_string(), v.to_string()))
|
|
}
|
|
|
|
fn urlencoded(s: &str) -> String {
|
|
// Minimal pass: percent-encode the few chars that break the query.
|
|
// Slugs and UUIDs don't contain them in practice, but be safe.
|
|
let mut out = String::with_capacity(s.len());
|
|
for ch in s.chars() {
|
|
match ch {
|
|
'&' | '=' | '?' | '#' | ' ' => {
|
|
out.push_str(&format!("%{:02X}", u32::from(ch)));
|
|
}
|
|
_ => out.push(ch),
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
async fn decode<T: for<'de> Deserialize<'de>>(resp: reqwest::Response) -> Result<T> {
|
|
if resp.status().is_success() {
|
|
return resp.json::<T>().await.context("parsing response body");
|
|
}
|
|
Err(server_error(resp).await)
|
|
}
|
|
|
|
/// Like `decode` but for endpoints whose 2xx response has no body
|
|
/// (204 No Content) — DELETE handlers, logout.
|
|
async fn decode_status(resp: reqwest::Response) -> Result<()> {
|
|
if resp.status().is_success() {
|
|
return Ok(());
|
|
}
|
|
Err(server_error(resp).await)
|
|
}
|
|
|
|
async fn server_error(resp: reqwest::Response) -> anyhow::Error {
|
|
let status = resp.status();
|
|
let body = resp.text().await.unwrap_or_default();
|
|
let msg = parse_error_body(&body).unwrap_or(body);
|
|
let hint = role_hint(status);
|
|
if hint.is_empty() {
|
|
anyhow!("HTTP {}: {}", status.as_u16(), msg)
|
|
} else {
|
|
anyhow!("HTTP {}: {} ({})", status.as_u16(), msg, hint)
|
|
}
|
|
}
|
|
|
|
fn parse_error_body(s: &str) -> Option<String> {
|
|
let v: Value = serde_json::from_str(s).ok()?;
|
|
let obj = v.as_object()?;
|
|
if let Some(m) = obj.get("message").and_then(Value::as_str) {
|
|
return Some(m.to_string());
|
|
}
|
|
if let Some(e) = obj.get("error").and_then(Value::as_str) {
|
|
return Some(e.to_string());
|
|
}
|
|
None
|
|
}
|
|
|
|
fn role_hint(status: StatusCode) -> &'static str {
|
|
match status {
|
|
StatusCode::FORBIDDEN => "your role may lack the required capability; check `pic whoami`",
|
|
StatusCode::UNAUTHORIZED => "token rejected; re-run `pic login`",
|
|
_ => "",
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn parse_kv_colon() {
|
|
let (k, v) = parse_kv_header("X-Foo: bar").unwrap();
|
|
assert_eq!(k, "X-Foo");
|
|
assert_eq!(v, "bar");
|
|
}
|
|
|
|
#[test]
|
|
fn parse_kv_equals() {
|
|
let (k, v) = parse_kv_header("X-Foo=bar").unwrap();
|
|
assert_eq!(k, "X-Foo");
|
|
assert_eq!(v, "bar");
|
|
}
|
|
|
|
#[test]
|
|
fn parse_kv_rejects_no_separator() {
|
|
assert!(parse_kv_header("X-Foo").is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn parse_kv_rejects_empty_name() {
|
|
assert!(parse_kv_header(": bar").is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn url_strip_trailing_slash() {
|
|
let c = Client::new("http://localhost:8000/", "pic_x").unwrap();
|
|
assert_eq!(c.url(), "http://localhost:8000");
|
|
}
|
|
|
|
#[test]
|
|
fn seg_escapes_path_delimiters() {
|
|
// A free-form segment can't break out into a new path segment,
|
|
// the query, or the fragment.
|
|
assert_eq!(seg("a/b"), "a%2Fb");
|
|
assert_eq!(seg("a?b"), "a%3Fb");
|
|
assert_eq!(seg("a#b"), "a%23b");
|
|
assert_eq!(seg("a b"), "a%20b");
|
|
// Ordinary slugs / UUIDs pass through unchanged.
|
|
assert_eq!(seg("my-app"), "my-app");
|
|
assert_eq!(
|
|
seg("4c8b8775-2a9e-4212-9187-a8f56a1b60e7"),
|
|
"4c8b8775-2a9e-4212-9187-a8f56a1b60e7"
|
|
);
|
|
}
|
|
}
|