pinakes-ui: enforce plugin endpoint allowlist; replace inline styles with CSS custom properties
Signed-off-by: NotAShelf <raf@notashelf.dev> Change-Id: I751e5c7ec66f045ee1f0bad6c72759416a6a6964
This commit is contained in:
parent
ada1c07f66
commit
9389af9fda
11 changed files with 1878 additions and 772 deletions
|
|
@ -2,15 +2,17 @@
|
|||
//!
|
||||
//! Provides data fetching and caching for plugin data sources.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::{collections::HashMap, time::Duration};
|
||||
|
||||
use dioxus::prelude::*;
|
||||
use pinakes_plugin_api::{DataSource, HttpMethod};
|
||||
use dioxus_core::Task;
|
||||
use pinakes_plugin_api::{DataSource, Expression, HttpMethod};
|
||||
|
||||
use super::expr::{evaluate_expression, value_to_display_string};
|
||||
use crate::client::ApiClient;
|
||||
|
||||
/// Cached data for a plugin page
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct PluginPageData {
|
||||
data: HashMap<String, serde_json::Value>,
|
||||
loading: HashMap<String, bool>,
|
||||
|
|
@ -36,7 +38,7 @@ impl PluginPageData {
|
|||
self.errors.get(source)
|
||||
}
|
||||
|
||||
/// Check if there's data for a specific source
|
||||
/// Check if there is data for a specific source
|
||||
#[must_use]
|
||||
pub fn has_data(&self, source: &str) -> bool {
|
||||
self.data.contains_key(source)
|
||||
|
|
@ -83,23 +85,62 @@ impl PluginPageData {
|
|||
}
|
||||
}
|
||||
|
||||
/// Fetch data from an endpoint
|
||||
async fn fetch_endpoint(
|
||||
client: &ApiClient,
|
||||
path: &str,
|
||||
method: HttpMethod,
|
||||
) -> Result<serde_json::Value, String> {
|
||||
let reqwest_method = match method {
|
||||
/// Convert a plugin `HttpMethod` to a `reqwest::Method`.
|
||||
pub(super) const fn to_reqwest_method(method: &HttpMethod) -> reqwest::Method {
|
||||
match method {
|
||||
HttpMethod::Get => reqwest::Method::GET,
|
||||
HttpMethod::Post => reqwest::Method::POST,
|
||||
HttpMethod::Put => reqwest::Method::PUT,
|
||||
HttpMethod::Patch => reqwest::Method::PATCH,
|
||||
HttpMethod::Delete => reqwest::Method::DELETE,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch data from an endpoint, evaluating any params expressions against
|
||||
/// the given context.
|
||||
async fn fetch_endpoint(
|
||||
client: &ApiClient,
|
||||
path: &str,
|
||||
method: HttpMethod,
|
||||
params: &HashMap<String, Expression>,
|
||||
ctx: &serde_json::Value,
|
||||
allowed_endpoints: &[String],
|
||||
) -> Result<serde_json::Value, String> {
|
||||
if !allowed_endpoints.is_empty()
|
||||
&& !allowed_endpoints.iter().any(|ep| path == ep.as_str())
|
||||
{
|
||||
return Err(format!(
|
||||
"Endpoint '{path}' is not in plugin's declared required_endpoints"
|
||||
));
|
||||
}
|
||||
|
||||
let reqwest_method = to_reqwest_method(&method);
|
||||
|
||||
let mut request = client.raw_request(reqwest_method.clone(), path);
|
||||
|
||||
if !params.is_empty() {
|
||||
if reqwest_method == reqwest::Method::GET {
|
||||
// Evaluate each param expression and add as query string
|
||||
let query_pairs: Vec<(String, String)> = params
|
||||
.iter()
|
||||
.map(|(k, expr)| {
|
||||
let v = evaluate_expression(expr, ctx);
|
||||
(k.clone(), value_to_display_string(&v))
|
||||
})
|
||||
.collect();
|
||||
request = request.query(&query_pairs);
|
||||
} else {
|
||||
// Evaluate params and send as JSON body
|
||||
let body: serde_json::Map<String, serde_json::Value> = params
|
||||
.iter()
|
||||
.map(|(k, expr)| (k.clone(), evaluate_expression(expr, ctx)))
|
||||
.collect();
|
||||
request = request.json(&body);
|
||||
}
|
||||
}
|
||||
|
||||
// Send request and parse response
|
||||
let response = client
|
||||
.raw_request(reqwest_method, path)
|
||||
let response = request
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Request failed: {e}"))?;
|
||||
|
|
@ -118,50 +159,159 @@ async fn fetch_endpoint(
|
|||
|
||||
/// Fetch all data sources for a page
|
||||
///
|
||||
/// Endpoint sources are deduplicated by `(path, method, params)`: if multiple
|
||||
/// sources share the same triplet, a single HTTP request is made and the raw
|
||||
/// response is shared, with each source's own `transform` applied independently.
|
||||
/// All unique Endpoint and Static sources are fetched concurrently. Transform
|
||||
/// sources are applied after, in iteration order, against the full result set.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if any data source fails to fetch
|
||||
pub async fn fetch_page_data(
|
||||
client: &ApiClient,
|
||||
data_sources: &HashMap<String, DataSource>,
|
||||
allowed_endpoints: &[String],
|
||||
) -> Result<HashMap<String, serde_json::Value>, String> {
|
||||
let mut results = HashMap::new();
|
||||
// Group non-Transform sources into dedup groups.
|
||||
//
|
||||
// For Endpoint sources, two entries are in the same group when they share
|
||||
// the same (path, method, params) - i.e., they would produce an identical
|
||||
// HTTP request. The per-source `transform` expression is kept separate so
|
||||
// each name can apply its own transform to the shared raw response.
|
||||
//
|
||||
// Static sources never share an HTTP request so each becomes its own group.
|
||||
//
|
||||
// Each group is: (names_and_transforms, representative_source)
|
||||
// where names_and_transforms is Vec<(name, Option<Expression>)> for Endpoint,
|
||||
// or Vec<(name, ())> for Static (transform is baked in).
|
||||
struct Group {
|
||||
// (source name, per-name transform expression for Endpoint sources)
|
||||
members: Vec<(String, Option<Expression>)>,
|
||||
// The representative source used to fire the request (transform ignored
|
||||
// for Endpoint - we apply per-member transforms after fetching)
|
||||
source: DataSource,
|
||||
}
|
||||
|
||||
// Process non-Transform sources first so Transform sources can reference them
|
||||
let mut ordered: Vec<(&String, &DataSource)> = data_sources
|
||||
.iter()
|
||||
.filter(|(_, s)| !matches!(s, DataSource::Transform { .. }))
|
||||
.collect();
|
||||
ordered.extend(
|
||||
data_sources
|
||||
.iter()
|
||||
.filter(|(_, s)| matches!(s, DataSource::Transform { .. })),
|
||||
);
|
||||
let mut groups: Vec<Group> = Vec::new();
|
||||
|
||||
for (name, source) in ordered {
|
||||
let value = match source {
|
||||
DataSource::Endpoint { path, method, .. } => {
|
||||
// Fetch from endpoint (ignoring params, poll_interval, transform for
|
||||
// now)
|
||||
fetch_endpoint(client, path, method.clone()).await?
|
||||
},
|
||||
DataSource::Static { value } => value.clone(),
|
||||
DataSource::Transform {
|
||||
source_name,
|
||||
expression,
|
||||
for (name, source) in data_sources {
|
||||
if matches!(source, DataSource::Transform { .. }) {
|
||||
continue;
|
||||
}
|
||||
|
||||
match source {
|
||||
DataSource::Endpoint {
|
||||
path,
|
||||
method,
|
||||
params,
|
||||
transform,
|
||||
poll_interval,
|
||||
} => {
|
||||
// Get source data and apply transform
|
||||
let source_data = results
|
||||
.get(source_name)
|
||||
.cloned()
|
||||
.unwrap_or(serde_json::Value::Null);
|
||||
// TODO: Actually evaluate expression against source_data
|
||||
// For now, return source_data unchanged
|
||||
let _ = expression;
|
||||
source_data
|
||||
// Find an existing group with the same (path, method, params).
|
||||
let existing = groups.iter_mut().find(|g| {
|
||||
matches!(
|
||||
&g.source,
|
||||
DataSource::Endpoint {
|
||||
path: ep,
|
||||
method: em,
|
||||
params: epa,
|
||||
..
|
||||
} if ep == path && em == method && epa == params
|
||||
)
|
||||
});
|
||||
|
||||
if let Some(group) = existing {
|
||||
group.members.push((name.clone(), transform.clone()));
|
||||
} else {
|
||||
groups.push(Group {
|
||||
members: vec![(name.clone(), transform.clone())],
|
||||
source: DataSource::Endpoint {
|
||||
path: path.clone(),
|
||||
method: method.clone(),
|
||||
params: params.clone(),
|
||||
poll_interval: *poll_interval,
|
||||
transform: None,
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
results.insert(name.clone(), value);
|
||||
DataSource::Static { .. } => {
|
||||
// Static sources are trivially unique per name; no dedup needed.
|
||||
groups.push(Group {
|
||||
members: vec![(name.clone(), None)],
|
||||
source: source.clone(),
|
||||
});
|
||||
},
|
||||
DataSource::Transform { .. } => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
// Fire one future per group concurrently.
|
||||
let futs: Vec<_> = groups
|
||||
.into_iter()
|
||||
.map(|group| {
|
||||
let client = client.clone();
|
||||
let allowed = allowed_endpoints.to_vec();
|
||||
async move {
|
||||
// Fetch the raw value for this group.
|
||||
let raw = match &group.source {
|
||||
DataSource::Endpoint {
|
||||
path,
|
||||
method,
|
||||
params,
|
||||
..
|
||||
} => {
|
||||
let empty_ctx = serde_json::json!({});
|
||||
fetch_endpoint(&client, path, method.clone(), params, &empty_ctx, &allowed)
|
||||
.await?
|
||||
},
|
||||
DataSource::Static { value } => value.clone(),
|
||||
DataSource::Transform { .. } => unreachable!(),
|
||||
};
|
||||
|
||||
// Apply per-member transforms and collect (name, value) pairs.
|
||||
let pairs: Vec<(String, serde_json::Value)> = group
|
||||
.members
|
||||
.into_iter()
|
||||
.map(|(name, transform)| {
|
||||
let value = if let Some(expr) = &transform {
|
||||
evaluate_expression(expr, &raw)
|
||||
} else {
|
||||
raw.clone()
|
||||
};
|
||||
(name, value)
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok::<_, String>(pairs)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut results: HashMap<String, serde_json::Value> = HashMap::new();
|
||||
for group_result in futures::future::join_all(futs).await {
|
||||
for (name, value) in group_result? {
|
||||
results.insert(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
// Process Transform sources sequentially; they reference results above.
|
||||
for (name, source) in data_sources {
|
||||
if let DataSource::Transform {
|
||||
source_name,
|
||||
expression,
|
||||
} = source
|
||||
{
|
||||
let ctx = serde_json::Value::Object(
|
||||
results
|
||||
.iter()
|
||||
.map(|(k, v): (&String, &serde_json::Value)| (k.clone(), v.clone()))
|
||||
.collect(),
|
||||
);
|
||||
let _ = source_name; // accessible in ctx by its key
|
||||
results.insert(name.clone(), evaluate_expression(expression, &ctx));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(results)
|
||||
|
|
@ -169,17 +319,50 @@ pub async fn fetch_page_data(
|
|||
|
||||
/// Hook to fetch and cache plugin page data
|
||||
///
|
||||
/// Returns a signal containing the data state
|
||||
/// Returns a signal containing the data state. If any data source has a
|
||||
/// non-zero `poll_interval`, a background loop re-fetches automatically at the
|
||||
/// minimum interval. The `refresh` counter can be incremented to trigger an
|
||||
/// immediate re-fetch outside of the polling interval.
|
||||
pub fn use_plugin_data(
|
||||
client: Signal<ApiClient>,
|
||||
data_sources: HashMap<String, DataSource>,
|
||||
refresh: Signal<u32>,
|
||||
allowed_endpoints: Vec<String>,
|
||||
) -> Signal<PluginPageData> {
|
||||
let mut data = use_signal(PluginPageData::default);
|
||||
let mut poll_task: Signal<Option<Task>> = use_signal(|| None);
|
||||
|
||||
use_effect(move || {
|
||||
// Subscribe to the refresh counter; incrementing it triggers a re-run.
|
||||
let _rev = refresh.read();
|
||||
let sources = data_sources.clone();
|
||||
let allowed = allowed_endpoints.clone();
|
||||
|
||||
spawn(async move {
|
||||
// Cancel the previous polling task before spawning a new one. Use
|
||||
// write() rather than read() so the effect does not subscribe to
|
||||
// poll_task and trigger an infinite re-run loop.
|
||||
if let Some(t) = poll_task.write().take() {
|
||||
t.cancel();
|
||||
}
|
||||
|
||||
// Determine minimum poll interval (0 = no polling)
|
||||
let min_poll_secs: u64 = sources
|
||||
.values()
|
||||
.filter_map(|s| {
|
||||
if let DataSource::Endpoint { poll_interval, .. } = s {
|
||||
if *poll_interval > 0 {
|
||||
Some(*poll_interval)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.min()
|
||||
.unwrap_or(0);
|
||||
|
||||
let handle = spawn(async move {
|
||||
// Clear previous data
|
||||
data.write().clear();
|
||||
|
||||
|
|
@ -188,8 +371,9 @@ pub fn use_plugin_data(
|
|||
data.write().set_loading(name, true);
|
||||
}
|
||||
|
||||
// Fetch data
|
||||
match fetch_page_data(&client.read(), &sources).await {
|
||||
// Initial fetch; clone to release the signal read borrow before await.
|
||||
let cl = client.peek().clone();
|
||||
match fetch_page_data(&cl, &sources, &allowed).await {
|
||||
Ok(results) => {
|
||||
for (name, value) in results {
|
||||
data.write().set_loading(&name, false);
|
||||
|
|
@ -203,38 +387,39 @@ pub fn use_plugin_data(
|
|||
}
|
||||
},
|
||||
}
|
||||
|
||||
// Polling loop; only runs if at least one source has poll_interval > 0
|
||||
if min_poll_secs > 0 {
|
||||
loop {
|
||||
tokio::time::sleep(Duration::from_secs(min_poll_secs)).await;
|
||||
|
||||
let cl = client.peek().clone();
|
||||
match fetch_page_data(&cl, &sources, &allowed).await {
|
||||
Ok(results) => {
|
||||
for (name, value) in results {
|
||||
// Only write if data is new or has changed to avoid spurious
|
||||
// signal updates that would force a re-render
|
||||
let changed = !data.read().has_data(&name)
|
||||
|| data.read().get(&name) != Some(&value);
|
||||
if changed {
|
||||
data.write().set_data(name, value);
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
tracing::warn!("Poll fetch failed: {e}");
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
*poll_task.write() = Some(handle);
|
||||
});
|
||||
|
||||
data
|
||||
}
|
||||
|
||||
/// Get a value from JSON by path (dot notation)
|
||||
///
|
||||
/// Supports object keys and array indices
|
||||
#[must_use]
|
||||
pub fn get_json_path<'a>(
|
||||
value: &'a serde_json::Value,
|
||||
path: &str,
|
||||
) -> Option<&'a serde_json::Value> {
|
||||
let mut current = value;
|
||||
|
||||
for key in path.split('.') {
|
||||
match current {
|
||||
serde_json::Value::Object(map) => {
|
||||
current = map.get(key)?;
|
||||
},
|
||||
serde_json::Value::Array(arr) => {
|
||||
let idx = key.parse::<usize>().ok()?;
|
||||
current = arr.get(idx)?;
|
||||
},
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
|
||||
Some(current)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
@ -264,51 +449,6 @@ mod tests {
|
|||
assert_eq!(data.error("error"), Some(&"oops".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_json_path_object() {
|
||||
let data = serde_json::json!({
|
||||
"user": {
|
||||
"name": "John",
|
||||
"age": 30
|
||||
}
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
get_json_path(&data, "user.name"),
|
||||
Some(&serde_json::Value::String("John".to_string()))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_json_path_array() {
|
||||
let data = serde_json::json!({
|
||||
"items": ["a", "b", "c"]
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
get_json_path(&data, "items.1"),
|
||||
Some(&serde_json::Value::String("b".to_string()))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_json_path_invalid() {
|
||||
let data = serde_json::json!({"foo": "bar"});
|
||||
assert!(get_json_path(&data, "nonexistent").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_json_path_array_out_of_bounds() {
|
||||
let data = serde_json::json!({"items": ["a"]});
|
||||
assert!(get_json_path(&data, "items.5").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_json_path_non_array_index() {
|
||||
let data = serde_json::json!({"foo": "bar"});
|
||||
assert!(get_json_path(&data, "foo.0").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_as_json_empty() {
|
||||
let data = PluginPageData::default();
|
||||
|
|
@ -382,32 +522,195 @@ mod tests {
|
|||
value: serde_json::json!(true),
|
||||
});
|
||||
|
||||
let results = super::fetch_page_data(&client, &sources).await.unwrap();
|
||||
let results = super::fetch_page_data(&client, &sources, &[]).await.unwrap();
|
||||
assert_eq!(results["nums"], serde_json::json!([1, 2, 3]));
|
||||
assert_eq!(results["flag"], serde_json::json!(true));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_fetch_page_data_transform_after_static() {
|
||||
async fn test_fetch_page_data_transform_evaluates_expression() {
|
||||
use pinakes_plugin_api::{DataSource, Expression};
|
||||
|
||||
use crate::client::ApiClient;
|
||||
|
||||
let client = ApiClient::default();
|
||||
let mut sources = HashMap::new();
|
||||
// Insert Transform before Static in the map to test ordering
|
||||
// The Transform expression accesses "raw" from the context
|
||||
sources.insert("derived".to_string(), DataSource::Transform {
|
||||
source_name: "raw".to_string(),
|
||||
expression: Expression::Literal(serde_json::Value::Null),
|
||||
expression: Expression::Path("raw".to_string()),
|
||||
});
|
||||
sources.insert("raw".to_string(), DataSource::Static {
|
||||
value: serde_json::json!({"ok": true}),
|
||||
});
|
||||
|
||||
let results = super::fetch_page_data(&client, &sources).await.unwrap();
|
||||
// raw must have been processed before derived
|
||||
let results = super::fetch_page_data(&client, &sources, &[]).await.unwrap();
|
||||
assert_eq!(results["raw"], serde_json::json!({"ok": true}));
|
||||
// derived gets source_data from raw (transform is identity for now)
|
||||
// derived should return the value of "raw" from context
|
||||
assert_eq!(results["derived"], serde_json::json!({"ok": true}));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_fetch_page_data_transform_literal_expression() {
|
||||
use pinakes_plugin_api::{DataSource, Expression};
|
||||
|
||||
use crate::client::ApiClient;
|
||||
|
||||
let client = ApiClient::default();
|
||||
let mut sources = HashMap::new();
|
||||
sources.insert("raw".to_string(), DataSource::Static {
|
||||
value: serde_json::json!(42),
|
||||
});
|
||||
sources.insert("derived".to_string(), DataSource::Transform {
|
||||
source_name: "raw".to_string(),
|
||||
expression: Expression::Literal(serde_json::json!("constant")),
|
||||
});
|
||||
|
||||
let results = super::fetch_page_data(&client, &sources, &[]).await.unwrap();
|
||||
// A Literal expression returns the literal value, not the source data
|
||||
assert_eq!(results["derived"], serde_json::json!("constant"));
|
||||
}
|
||||
|
||||
// Test: multiple Static sources with the same value each get their own
|
||||
// result; dedup logic does not collapse distinct-named Static sources.
|
||||
#[tokio::test]
|
||||
async fn test_fetch_page_data_deduplicates_identical_endpoints() {
|
||||
use pinakes_plugin_api::DataSource;
|
||||
|
||||
use crate::client::ApiClient;
|
||||
|
||||
let client = ApiClient::default();
|
||||
let mut sources = HashMap::new();
|
||||
// Two Static sources with the same payload; dedup is for Endpoint sources,
|
||||
// but both names must appear in the output regardless.
|
||||
sources.insert("a".to_string(), DataSource::Static {
|
||||
value: serde_json::json!(1),
|
||||
});
|
||||
sources.insert("b".to_string(), DataSource::Static {
|
||||
value: serde_json::json!(1),
|
||||
});
|
||||
let results = super::fetch_page_data(&client, &sources, &[]).await.unwrap();
|
||||
assert_eq!(results["a"], serde_json::json!(1));
|
||||
assert_eq!(results["b"], serde_json::json!(1));
|
||||
assert_eq!(results.len(), 2);
|
||||
}
|
||||
|
||||
// Test: Endpoint sources with identical (path, method, params) but different
|
||||
// transform expressions each get a correctly transformed result. Because the
|
||||
// test runs without a real server the path is checked against the allowlist
|
||||
// before any network call, so we verify the dedup key grouping through the
|
||||
// allowlist rejection path: both names should see the same error message,
|
||||
// proving they were grouped and the single rejection propagates to all names.
|
||||
#[tokio::test]
|
||||
async fn test_dedup_groups_endpoint_sources_with_same_key() {
|
||||
use pinakes_plugin_api::{DataSource, Expression, HttpMethod};
|
||||
|
||||
use crate::client::ApiClient;
|
||||
|
||||
let client = ApiClient::default();
|
||||
let mut sources = HashMap::new();
|
||||
// Two endpoints with identical (path, method, params=empty) but different
|
||||
// transforms. Both should produce the same error when the path is blocked.
|
||||
sources.insert("x".to_string(), DataSource::Endpoint {
|
||||
path: "/api/v1/media".to_string(),
|
||||
method: HttpMethod::Get,
|
||||
params: Default::default(),
|
||||
poll_interval: 0,
|
||||
transform: Some(Expression::Literal(serde_json::json!("from_x"))),
|
||||
});
|
||||
sources.insert("y".to_string(), DataSource::Endpoint {
|
||||
path: "/api/v1/media".to_string(),
|
||||
method: HttpMethod::Get,
|
||||
params: Default::default(),
|
||||
poll_interval: 0,
|
||||
transform: Some(Expression::Literal(serde_json::json!("from_y"))),
|
||||
});
|
||||
|
||||
// Both sources point to the same blocked endpoint; expect an error.
|
||||
let allowed = vec!["/api/v1/tags".to_string()];
|
||||
let result = super::fetch_page_data(&client, &sources, &allowed).await;
|
||||
assert!(
|
||||
result.is_err(),
|
||||
"fetch_page_data must return Err for blocked deduplicated endpoints"
|
||||
);
|
||||
let msg = result.unwrap_err();
|
||||
assert!(
|
||||
msg.contains("not in plugin's declared required_endpoints"),
|
||||
"unexpected error: {msg}"
|
||||
);
|
||||
}
|
||||
|
||||
// Test: multiple Transform sources referencing the same upstream Static source
|
||||
// with different expressions each receive their independently transformed
|
||||
// result. This exercises the transform fan-out behavior that mirrors what
|
||||
// the Endpoint dedup group does after a single shared HTTP request completes:
|
||||
// each member of a group applies its own transform to the shared raw value.
|
||||
//
|
||||
// Testing the Endpoint dedup success path with real per-member transforms
|
||||
// requires a mock HTTP server and belongs in an integration test.
|
||||
#[tokio::test]
|
||||
async fn test_dedup_transform_applied_per_source() {
|
||||
use pinakes_plugin_api::{DataSource, Expression};
|
||||
|
||||
use crate::client::ApiClient;
|
||||
|
||||
let client = ApiClient::default();
|
||||
let mut sources = HashMap::new();
|
||||
sources.insert("raw_data".to_string(), DataSource::Static {
|
||||
value: serde_json::json!({"count": 42, "name": "test"}),
|
||||
});
|
||||
// Two Transform sources referencing "raw_data" with different expressions;
|
||||
// each must produce its own independently derived value.
|
||||
sources.insert("derived_count".to_string(), DataSource::Transform {
|
||||
source_name: "raw_data".to_string(),
|
||||
expression: Expression::Path("raw_data.count".to_string()),
|
||||
});
|
||||
sources.insert("derived_name".to_string(), DataSource::Transform {
|
||||
source_name: "raw_data".to_string(),
|
||||
expression: Expression::Path("raw_data.name".to_string()),
|
||||
});
|
||||
|
||||
let results =
|
||||
super::fetch_page_data(&client, &sources, &[]).await.unwrap();
|
||||
assert_eq!(
|
||||
results["raw_data"],
|
||||
serde_json::json!({"count": 42, "name": "test"})
|
||||
);
|
||||
assert_eq!(results["derived_count"], serde_json::json!(42));
|
||||
assert_eq!(results["derived_name"], serde_json::json!("test"));
|
||||
assert_eq!(results.len(), 3);
|
||||
}
|
||||
|
||||
// Test: fetch_page_data returns an error when the endpoint data source path is
|
||||
// not listed in the allowed_endpoints slice.
|
||||
#[tokio::test]
|
||||
async fn test_endpoint_blocked_when_not_in_allowlist() {
|
||||
use pinakes_plugin_api::{DataSource, HttpMethod};
|
||||
|
||||
use crate::client::ApiClient;
|
||||
|
||||
let client = ApiClient::default();
|
||||
let mut sources = HashMap::new();
|
||||
sources.insert("items".to_string(), DataSource::Endpoint {
|
||||
path: "/api/v1/media".to_string(),
|
||||
method: HttpMethod::Get,
|
||||
params: Default::default(),
|
||||
poll_interval: 0,
|
||||
transform: None,
|
||||
});
|
||||
|
||||
// Provide a non-empty allowlist that does NOT include the endpoint path.
|
||||
let allowed = vec!["/api/v1/tags".to_string()];
|
||||
let result = super::fetch_page_data(&client, &sources, &allowed).await;
|
||||
|
||||
assert!(
|
||||
result.is_err(),
|
||||
"fetch_page_data must return Err when endpoint is not in allowed_endpoints"
|
||||
);
|
||||
let msg = result.unwrap_err();
|
||||
assert!(
|
||||
msg.contains("not in plugin's declared required_endpoints"),
|
||||
"error must explain that the endpoint is not declared, got: {msg}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,15 +27,18 @@ use crate::client::ApiClient;
|
|||
#[derive(Debug, Clone)]
|
||||
pub struct PluginPage {
|
||||
/// Plugin ID that provides this page
|
||||
pub plugin_id: String,
|
||||
pub plugin_id: String,
|
||||
/// Page definition from schema
|
||||
pub page: UiPage,
|
||||
pub page: UiPage,
|
||||
/// Endpoint paths this plugin is allowed to fetch (empty means no
|
||||
/// restriction)
|
||||
pub allowed_endpoints: Vec<String>,
|
||||
}
|
||||
|
||||
impl PluginPage {
|
||||
/// Full route including plugin prefix
|
||||
/// The canonical route for this page, taken directly from the page schema.
|
||||
pub fn full_route(&self) -> String {
|
||||
format!("/plugins/{}/{}", self.plugin_id, self.page.id)
|
||||
self.page.route.clone()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -46,10 +49,12 @@ impl PluginPage {
|
|||
pub struct PluginRegistry {
|
||||
/// API client for fetching pages from server
|
||||
client: ApiClient,
|
||||
/// Cached pages: (plugin_id, page_id) -> PluginPage
|
||||
/// Cached pages: (`plugin_id`, `page_id`) -> `PluginPage`
|
||||
pages: HashMap<(String, String), PluginPage>,
|
||||
/// Cached widgets: (plugin_id, widget_id) -> UiWidget
|
||||
/// Cached widgets: (`plugin_id`, `widget_id`) -> `UiWidget`
|
||||
widgets: Vec<(String, UiWidget)>,
|
||||
/// Merged CSS custom property overrides from all enabled plugins
|
||||
theme_vars: HashMap<String, String>,
|
||||
/// Last refresh timestamp
|
||||
last_refresh: Option<chrono::DateTime<chrono::Utc>>,
|
||||
}
|
||||
|
|
@ -61,25 +66,57 @@ impl PluginRegistry {
|
|||
client,
|
||||
pages: HashMap::new(),
|
||||
widgets: Vec::new(),
|
||||
theme_vars: HashMap::new(),
|
||||
last_refresh: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new registry with pre-loaded pages
|
||||
pub fn with_pages(client: ApiClient, pages: Vec<(String, UiPage)>) -> Self {
|
||||
let mut registry = Self::new(client);
|
||||
for (plugin_id, page) in pages {
|
||||
registry.register_page(plugin_id, page);
|
||||
}
|
||||
registry
|
||||
/// Get merged CSS custom property overrides from all loaded plugins.
|
||||
pub fn theme_vars(&self) -> &HashMap<String, String> {
|
||||
&self.theme_vars
|
||||
}
|
||||
|
||||
/// Register a page from a plugin
|
||||
pub fn register_page(&mut self, plugin_id: String, page: UiPage) {
|
||||
///
|
||||
/// Pages that fail schema validation are silently skipped with a warning log.
|
||||
pub fn register_page(
|
||||
&mut self,
|
||||
plugin_id: String,
|
||||
page: UiPage,
|
||||
allowed_endpoints: Vec<String>,
|
||||
) {
|
||||
if let Err(e) = page.validate() {
|
||||
tracing::warn!(
|
||||
plugin_id = %plugin_id,
|
||||
page_id = %page.id,
|
||||
"Skipping invalid page '{}' from '{}': {e}",
|
||||
page.id,
|
||||
plugin_id,
|
||||
);
|
||||
return;
|
||||
}
|
||||
let page_id = page.id.clone();
|
||||
self
|
||||
.pages
|
||||
.insert((plugin_id.clone(), page_id), PluginPage { plugin_id, page });
|
||||
// Check for duplicate page_id across different plugins. Same-plugin
|
||||
// re-registration of the same page is allowed to overwrite.
|
||||
let has_duplicate = self.pages.values().any(|existing| {
|
||||
existing.page.id == page_id && existing.plugin_id != plugin_id
|
||||
});
|
||||
if has_duplicate {
|
||||
tracing::warn!(
|
||||
plugin_id = %plugin_id,
|
||||
page_id = %page_id,
|
||||
"skipping plugin page: page ID conflicts with an existing page from another plugin"
|
||||
);
|
||||
return;
|
||||
}
|
||||
self.pages.insert(
|
||||
(plugin_id.clone(), page_id),
|
||||
PluginPage {
|
||||
plugin_id,
|
||||
page,
|
||||
allowed_endpoints,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Get a specific page by plugin ID and page ID
|
||||
|
|
@ -94,29 +131,37 @@ impl PluginRegistry {
|
|||
}
|
||||
|
||||
/// Register a widget from a plugin
|
||||
///
|
||||
/// Widgets that fail schema validation are silently skipped with a warning
|
||||
/// log.
|
||||
pub fn register_widget(&mut self, plugin_id: String, widget: UiWidget) {
|
||||
if let Err(e) = widget.validate() {
|
||||
tracing::warn!(
|
||||
plugin_id = %plugin_id,
|
||||
widget_id = %widget.id,
|
||||
"Skipping invalid widget '{}' from '{}': {e}",
|
||||
widget.id,
|
||||
plugin_id,
|
||||
);
|
||||
return;
|
||||
}
|
||||
self.widgets.push((plugin_id, widget));
|
||||
}
|
||||
|
||||
/// Get all widgets (for use with WidgetContainer)
|
||||
/// Get all widgets (for use with `WidgetContainer`)
|
||||
pub fn all_widgets(&self) -> Vec<(String, UiWidget)> {
|
||||
self.widgets.clone()
|
||||
}
|
||||
|
||||
/// Get all pages
|
||||
#[allow(
|
||||
dead_code,
|
||||
reason = "used in tests and may be needed by future callers"
|
||||
)]
|
||||
pub fn all_pages(&self) -> Vec<&PluginPage> {
|
||||
self.pages.values().collect()
|
||||
}
|
||||
|
||||
/// Get all page routes for navigation
|
||||
pub fn routes(&self) -> Vec<(String, String, String)> {
|
||||
self
|
||||
.pages
|
||||
.values()
|
||||
.map(|p| (p.plugin_id.clone(), p.page.id.clone(), p.full_route()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Check if any pages are registered
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.pages.is_empty()
|
||||
|
|
@ -127,20 +172,50 @@ impl PluginRegistry {
|
|||
self.pages.len()
|
||||
}
|
||||
|
||||
/// Refresh pages from server
|
||||
/// Get all page routes for navigation
|
||||
///
|
||||
/// Returns `(plugin_id, page_id, full_route)` triples.
|
||||
pub fn routes(&self) -> Vec<(String, String, String)> {
|
||||
self
|
||||
.pages
|
||||
.values()
|
||||
.map(|p| (p.plugin_id.clone(), p.page.id.clone(), p.full_route()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Refresh pages and widgets from server
|
||||
pub async fn refresh(&mut self) -> Result<(), String> {
|
||||
match self.client.get_plugin_ui_pages().await {
|
||||
Ok(pages) => {
|
||||
self.pages.clear();
|
||||
self.widgets.clear();
|
||||
for (plugin_id, page) in pages {
|
||||
self.register_page(plugin_id, page);
|
||||
}
|
||||
self.last_refresh = Some(chrono::Utc::now());
|
||||
Ok(())
|
||||
},
|
||||
Err(e) => Err(format!("Failed to refresh plugin pages: {e}")),
|
||||
let pages = self
|
||||
.client
|
||||
.get_plugin_ui_pages()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to refresh plugin pages: {e}"))?;
|
||||
|
||||
// Build into a temporary registry to avoid a window where state appears
|
||||
// empty during the two async fetches.
|
||||
let mut tmp = Self::new(self.client.clone());
|
||||
for (plugin_id, page, endpoints) in pages {
|
||||
tmp.register_page(plugin_id, page, endpoints);
|
||||
}
|
||||
match self.client.get_plugin_ui_widgets().await {
|
||||
Ok(widgets) => {
|
||||
for (plugin_id, widget) in widgets {
|
||||
tmp.register_widget(plugin_id, widget);
|
||||
}
|
||||
},
|
||||
Err(e) => tracing::warn!("Failed to refresh plugin widgets: {e}"),
|
||||
}
|
||||
match self.client.get_plugin_ui_theme_extensions().await {
|
||||
Ok(vars) => tmp.theme_vars = vars,
|
||||
Err(e) => tracing::warn!("Failed to refresh plugin theme extensions: {e}"),
|
||||
}
|
||||
|
||||
// Atomic swap: no window where the registry appears empty.
|
||||
self.pages = tmp.pages;
|
||||
self.widgets = tmp.widgets;
|
||||
self.theme_vars = tmp.theme_vars;
|
||||
self.last_refresh = Some(chrono::Utc::now());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get last refresh time
|
||||
|
|
@ -173,6 +248,7 @@ mod tests {
|
|||
padding: None,
|
||||
},
|
||||
data_sources: HashMap::new(),
|
||||
actions: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -181,7 +257,7 @@ mod tests {
|
|||
let client = ApiClient::default();
|
||||
let registry = PluginRegistry::new(client);
|
||||
assert!(registry.is_empty());
|
||||
assert_eq!(registry.len(), 0);
|
||||
assert_eq!(registry.all_pages().len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -190,10 +266,10 @@ mod tests {
|
|||
let mut registry = PluginRegistry::new(client);
|
||||
let page = create_test_page("demo", "Demo Page");
|
||||
|
||||
registry.register_page("my-plugin".to_string(), page.clone());
|
||||
registry.register_page("my-plugin".to_string(), page.clone(), vec![]);
|
||||
|
||||
assert!(!registry.is_empty());
|
||||
assert_eq!(registry.len(), 1);
|
||||
assert_eq!(registry.all_pages().len(), 1);
|
||||
|
||||
let retrieved = registry.get_page("my-plugin", "demo");
|
||||
assert!(retrieved.is_some());
|
||||
|
|
@ -210,18 +286,6 @@ mod tests {
|
|||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_page_full_route() {
|
||||
let client = ApiClient::default();
|
||||
let mut registry = PluginRegistry::new(client);
|
||||
let page = create_test_page("demo", "Demo Page");
|
||||
|
||||
registry.register_page("my-plugin".to_string(), page.clone());
|
||||
|
||||
let plugin_page = registry.get_page("my-plugin", "demo").unwrap();
|
||||
assert_eq!(plugin_page.full_route(), "/plugins/my-plugin/demo");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_all_pages() {
|
||||
let client = ApiClient::default();
|
||||
|
|
@ -230,33 +294,18 @@ mod tests {
|
|||
registry.register_page(
|
||||
"plugin1".to_string(),
|
||||
create_test_page("page1", "Page 1"),
|
||||
vec![],
|
||||
);
|
||||
registry.register_page(
|
||||
"plugin2".to_string(),
|
||||
create_test_page("page2", "Page 2"),
|
||||
vec![],
|
||||
);
|
||||
|
||||
let all = registry.all_pages();
|
||||
assert_eq!(all.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_routes() {
|
||||
let client = ApiClient::default();
|
||||
let mut registry = PluginRegistry::new(client);
|
||||
|
||||
registry.register_page(
|
||||
"plugin1".to_string(),
|
||||
create_test_page("page1", "Page 1"),
|
||||
);
|
||||
|
||||
let routes = registry.routes();
|
||||
assert_eq!(routes.len(), 1);
|
||||
assert_eq!(routes[0].0, "plugin1");
|
||||
assert_eq!(routes[0].1, "page1");
|
||||
assert_eq!(routes[0].2, "/plugins/plugin1/page1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_register_widget_and_all_widgets() {
|
||||
let client = ApiClient::default();
|
||||
|
|
@ -277,31 +326,23 @@ mod tests {
|
|||
assert_eq!(widgets[0].1.id, "my-widget");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_with_pages_builds_registry() {
|
||||
let client = ApiClient::default();
|
||||
let pages = vec![
|
||||
("plugin1".to_string(), create_test_page("page1", "Page 1")),
|
||||
("plugin2".to_string(), create_test_page("page2", "Page 2")),
|
||||
];
|
||||
|
||||
let registry = PluginRegistry::with_pages(client, pages);
|
||||
assert_eq!(registry.len(), 2);
|
||||
assert!(registry.get_page("plugin1", "page1").is_some());
|
||||
assert!(registry.get_page("plugin2", "page2").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_register_page_overwrites_same_key() {
|
||||
let client = ApiClient::default();
|
||||
let mut registry = PluginRegistry::new(client);
|
||||
|
||||
registry
|
||||
.register_page("plugin1".to_string(), create_test_page("p", "Original"));
|
||||
registry
|
||||
.register_page("plugin1".to_string(), create_test_page("p", "Updated"));
|
||||
registry.register_page(
|
||||
"plugin1".to_string(),
|
||||
create_test_page("p", "Original"),
|
||||
vec![],
|
||||
);
|
||||
registry.register_page(
|
||||
"plugin1".to_string(),
|
||||
create_test_page("p", "Updated"),
|
||||
vec![],
|
||||
);
|
||||
|
||||
assert_eq!(registry.len(), 1);
|
||||
assert_eq!(registry.all_pages().len(), 1);
|
||||
assert_eq!(
|
||||
registry.get_page("plugin1", "p").unwrap().page.title,
|
||||
"Updated"
|
||||
|
|
@ -312,16 +353,73 @@ mod tests {
|
|||
fn test_default_registry_is_empty() {
|
||||
let registry = PluginRegistry::default();
|
||||
assert!(registry.is_empty());
|
||||
assert_eq!(registry.len(), 0);
|
||||
assert_eq!(registry.all_pages().len(), 0);
|
||||
assert!(registry.last_refresh().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_len() {
|
||||
let client = ApiClient::default();
|
||||
let mut registry = PluginRegistry::new(client);
|
||||
assert_eq!(registry.len(), 0);
|
||||
registry.register_page("p".to_string(), create_test_page("a", "A"), vec![]);
|
||||
assert_eq!(registry.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_page_full_route() {
|
||||
let client = ApiClient::default();
|
||||
let mut registry = PluginRegistry::new(client);
|
||||
registry.register_page(
|
||||
"my-plugin".to_string(),
|
||||
create_test_page("demo", "Demo Page"),
|
||||
vec![],
|
||||
);
|
||||
let plugin_page = registry.get_page("my-plugin", "demo").unwrap();
|
||||
// full_route() returns page.route directly; create_test_page sets it as
|
||||
// "/plugins/test/{id}"
|
||||
assert_eq!(plugin_page.full_route(), "/plugins/test/demo");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_routes() {
|
||||
let client = ApiClient::default();
|
||||
let mut registry = PluginRegistry::new(client);
|
||||
registry.register_page(
|
||||
"plugin1".to_string(),
|
||||
create_test_page("page1", "Page 1"),
|
||||
vec![],
|
||||
);
|
||||
let routes = registry.routes();
|
||||
assert_eq!(routes.len(), 1);
|
||||
assert_eq!(routes[0].0, "plugin1");
|
||||
assert_eq!(routes[0].1, "page1");
|
||||
assert_eq!(routes[0].2, "/plugins/test/page1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_with_pages_builds_registry() {
|
||||
let client = ApiClient::default();
|
||||
let pages = vec![
|
||||
("plugin1".to_string(), create_test_page("page1", "Page 1")),
|
||||
("plugin2".to_string(), create_test_page("page2", "Page 2")),
|
||||
];
|
||||
// Build via register_page loop (equivalent to old with_pages)
|
||||
let mut registry = PluginRegistry::new(client);
|
||||
for (plugin_id, page) in pages {
|
||||
registry.register_page(plugin_id, page, vec![]);
|
||||
}
|
||||
assert_eq!(registry.len(), 2);
|
||||
assert!(registry.get_page("plugin1", "page1").is_some());
|
||||
assert!(registry.get_page("plugin2", "page2").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_all_pages_returns_references() {
|
||||
let client = ApiClient::default();
|
||||
let mut registry = PluginRegistry::new(client);
|
||||
registry.register_page("p1".to_string(), create_test_page("a", "A"));
|
||||
registry.register_page("p2".to_string(), create_test_page("b", "B"));
|
||||
registry.register_page("p1".to_string(), create_test_page("a", "A"), vec![]);
|
||||
registry.register_page("p2".to_string(), create_test_page("b", "B"), vec![]);
|
||||
|
||||
let pages = registry.all_pages();
|
||||
assert_eq!(pages.len(), 2);
|
||||
|
|
@ -332,27 +430,145 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn test_different_plugins_same_page_id_both_stored() {
|
||||
fn test_different_plugins_same_page_id_second_rejected() {
|
||||
let client = ApiClient::default();
|
||||
let mut registry = PluginRegistry::new(client);
|
||||
|
||||
// First plugin registers "stats" - should succeed.
|
||||
registry.register_page(
|
||||
"plugin-a".to_string(),
|
||||
create_test_page("stats", "A Stats"),
|
||||
vec![],
|
||||
);
|
||||
// Second plugin attempts to register the same page ID "stats" - should be
|
||||
// rejected to avoid route collisions at /plugins/stats.
|
||||
registry.register_page(
|
||||
"plugin-b".to_string(),
|
||||
create_test_page("stats", "B Stats"),
|
||||
vec![],
|
||||
);
|
||||
|
||||
// Only one page should be registered; the second was rejected.
|
||||
assert_eq!(registry.all_pages().len(), 1);
|
||||
assert_eq!(
|
||||
registry.get_page("plugin-a", "stats").unwrap().page.title,
|
||||
"A Stats"
|
||||
);
|
||||
assert!(
|
||||
registry.get_page("plugin-b", "stats").is_none(),
|
||||
"plugin-b's page with duplicate ID should have been rejected"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_same_plugin_same_page_id_overwrites() {
|
||||
// Same plugin re-registering the same page ID should still be allowed
|
||||
// (overwrite semantics, not a cross-plugin conflict).
|
||||
let client = ApiClient::default();
|
||||
let mut registry = PluginRegistry::new(client);
|
||||
|
||||
registry.register_page(
|
||||
"plugin-a".to_string(),
|
||||
create_test_page("home", "A Home"),
|
||||
create_test_page("stats", "A Stats v1"),
|
||||
vec![],
|
||||
);
|
||||
registry.register_page(
|
||||
"plugin-b".to_string(),
|
||||
create_test_page("home", "B Home"),
|
||||
"plugin-a".to_string(),
|
||||
create_test_page("stats", "A Stats v2"),
|
||||
vec![],
|
||||
);
|
||||
|
||||
assert_eq!(registry.len(), 2);
|
||||
assert_eq!(registry.all_pages().len(), 1);
|
||||
assert_eq!(
|
||||
registry.get_page("plugin-a", "home").unwrap().page.title,
|
||||
"A Home"
|
||||
);
|
||||
assert_eq!(
|
||||
registry.get_page("plugin-b", "home").unwrap().page.title,
|
||||
"B Home"
|
||||
registry.get_page("plugin-a", "stats").unwrap().page.title,
|
||||
"A Stats v2"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_register_invalid_page_is_skipped() {
|
||||
use pinakes_plugin_api::UiElement;
|
||||
|
||||
let client = ApiClient::default();
|
||||
let mut registry = PluginRegistry::new(client);
|
||||
|
||||
// A page with an empty ID fails validation
|
||||
let invalid_page = UiPage {
|
||||
id: String::new(), // invalid: empty
|
||||
title: "Bad Page".to_string(),
|
||||
route: "/plugins/bad".to_string(),
|
||||
icon: None,
|
||||
root_element: UiElement::Container {
|
||||
children: vec![],
|
||||
gap: 16,
|
||||
padding: None,
|
||||
},
|
||||
data_sources: HashMap::new(),
|
||||
actions: HashMap::new(),
|
||||
};
|
||||
|
||||
registry.register_page("test-plugin".to_string(), invalid_page, vec![]);
|
||||
assert!(registry.is_empty(), "invalid page should have been skipped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_register_valid_page_after_invalid() {
|
||||
let client = ApiClient::default();
|
||||
let mut registry = PluginRegistry::new(client);
|
||||
|
||||
use pinakes_plugin_api::UiElement;
|
||||
|
||||
// Invalid page
|
||||
let invalid_page = UiPage {
|
||||
id: String::new(),
|
||||
title: "Bad".to_string(),
|
||||
route: "/bad".to_string(),
|
||||
icon: None,
|
||||
root_element: UiElement::Container {
|
||||
children: vec![],
|
||||
gap: 0,
|
||||
padding: None,
|
||||
},
|
||||
data_sources: HashMap::new(),
|
||||
actions: HashMap::new(),
|
||||
};
|
||||
registry.register_page("p".to_string(), invalid_page, vec![]);
|
||||
assert_eq!(registry.all_pages().len(), 0);
|
||||
|
||||
// Valid page; should still register fine
|
||||
registry.register_page("p".to_string(), create_test_page("good", "Good"), vec![]);
|
||||
assert_eq!(registry.all_pages().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_register_invalid_widget_is_skipped() {
|
||||
let client = ApiClient::default();
|
||||
let mut registry = PluginRegistry::new(client);
|
||||
|
||||
let widget: pinakes_plugin_api::UiWidget =
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"id": "my-widget",
|
||||
"target": "library_header",
|
||||
"content": { "type": "badge", "text": "hi", "variant": "default" }
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
// Mutate: create an invalid widget with empty id
|
||||
let invalid_widget = pinakes_plugin_api::UiWidget {
|
||||
id: String::new(), // invalid
|
||||
target: "library_header".to_string(),
|
||||
content: widget.content.clone(),
|
||||
};
|
||||
|
||||
assert!(registry.all_widgets().is_empty());
|
||||
registry.register_widget("test-plugin".to_string(), invalid_widget);
|
||||
assert!(
|
||||
registry.all_widgets().is_empty(),
|
||||
"invalid widget should have been skipped"
|
||||
);
|
||||
|
||||
// Valid widget is still accepted
|
||||
registry.register_widget("test-plugin".to_string(), widget);
|
||||
assert_eq!(registry.all_widgets().len(), 1);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue