feat(dashboard): the targets page pages server-side with page size and total #541

Merged
sharang merged 1 commits from feat/targets-pagination into main 2026-10-09 13:18:21 +00:00
7 changed files with 300 additions and 20 deletions

No files matched your search

@@ -96,6 +96,7 @@ pub async fn list_targets(
let targets = match db
.onboarded_targets()
.find(query)
.sort(TargetFilter::sort())
.skip(skip)
.limit(params.limit)
.await
@@ -169,6 +170,13 @@ impl TargetFilter {
None => doc! {},
}
}
/// The list's order: oldest first by id (creation order, what the list
/// showed before it paged). Ids are unique, so the order is total and a
/// page never repeats or skips a target.
pub fn sort() -> mongodb::bson::Document {
doc! { "_id": 1 }
}
}
/// The newest scan run of each target in `target_ids`, in one query.
@@ -1018,4 +1026,17 @@ mod filter_tests {
};
assert_eq!(blank.to_query(), doc! {});
}
#[test]
fn the_list_pages_in_a_total_order_with_the_filter_beside_it() {
// `?project=p1&page=2&limit=1` feeds both extractors of the handler.
let uri: axum::http::Uri = "/api/v1/targets?project=p1&page=2&limit=1"
.parse()
.expect("uri");
let Query(params) = Query::<PaginationParams>::try_from_uri(&uri).expect("params");
let Query(filter) = Query::<TargetFilter>::try_from_uri(&uri).expect("filter");
assert_eq!((params.page, params.limit, params.skip()), (2, 1, 1));
assert_eq!(filter.to_query(), doc! { "project_ids": "p1" });
assert_eq!(TargetFilter::sort(), doc! { "_id": 1 });
}
}
@@ -222,3 +222,68 @@ async fn a_rejected_upload_leaves_no_file_behind() {
server.cleanup().await;
}
#[tokio::test]
async fn the_list_pages_with_a_total_after_the_project_filter() {
let server = TestServer::start().await;
let mut ids = Vec::new();
for name in ["page-a", "page-b", "page-c"] {
ids.push(firmware_target(&server, name).await);
}
// Projects are registry-owned, so put two targets in one directly.
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let targets = client
.database(&format!("{}_dev", server.db_name()))
.collection::<mongodb::bson::Document>("onboarded_targets");
for id in &ids[1..] {
let oid = mongodb::bson::oid::ObjectId::parse_str(id).unwrap();
let updated = targets
.update_one(
mongodb::bson::doc! { "_id": oid },
mongodb::bson::doc! { "$set": { "project_ids": ["p1"] } },
)
.await
.unwrap();
assert_eq!(updated.matched_count, 1);
}
let names = |body: &serde_json::Value| -> Vec<String> {
body["data"]
.as_array()
.unwrap()
.iter()
.map(|t| t["name"].as_str().unwrap().to_string())
.collect()
};
let page = |query: &'static str| {
let server = &server;
async move {
let resp = server.get(&format!("/api/v1/targets?{query}")).await;
assert_eq!(resp.status(), 200);
resp.json::<serde_json::Value>().await.unwrap()
}
};
// Creation order, two to a page, the total over every page.
let first = page("limit=2&page=1").await;
assert_eq!(names(&first), ["page-a", "page-b"]);
assert_eq!(first["total"], 3);
assert_eq!(first["page"], 1);
let second = page("limit=2&page=2").await;
assert_eq!(names(&second), ["page-c"]);
assert_eq!(second["total"], 3);
// The filter applies before paging: the total counts the project only.
let in_project = page("project=p1&limit=1&page=2").await;
assert_eq!(names(&in_project), ["page-c"]);
assert_eq!(in_project["total"], 2);
// A page past the end is empty but still knows the total.
let past = page("limit=2&page=9").await;
assert!(names(&past).is_empty());
assert_eq!(past["total"], 3);
server.cleanup().await;
}
+18
View File
@@ -4748,6 +4748,24 @@ tbody tr:last-child td {
cursor: pointer;
}
/* Under the list: how many targets, and how many a page shows. */
.targets-pager {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
margin-top: 14px;
}
.targets-total {
font-size: 13px;
color: var(--text-secondary);
}
.targets-pager .project-filter select {
min-width: 0;
}
.targets-row:hover td {
background: var(--bg-card-hover);
}
@@ -1,11 +1,15 @@
use dioxus::prelude::*;
use crate::i18n::texts::common;
use crate::i18n::use_lang;
#[component]
pub fn Pagination(
current_page: u64,
total_pages: u64,
on_page_change: EventHandler<u64>,
) -> Element {
let lang = use_lang()();
if total_pages <= 1 {
return rsx! {};
}
@@ -16,17 +20,17 @@ pub fn Pagination(
class: "btn btn-ghost",
disabled: current_page <= 1,
onclick: move |_| on_page_change.call(current_page.saturating_sub(1)),
"Previous"
{common::PREVIOUS.get(lang)}
}
span {
style: "color: var(--text-secondary); font-size: 14px;",
"Page {current_page} of {total_pages}"
{common::page_of(current_page, total_pages, lang)}
}
button {
class: "btn btn-ghost",
disabled: current_page >= total_pages,
onclick: move |_| on_page_change.call(current_page + 1),
"Next"
{common::NEXT.get(lang)}
}
}
}
+58
View File
@@ -17,6 +17,27 @@ pub mod common {
de: "Wird geladen …",
en: "Loading...",
};
pub const PREVIOUS: Text = Text {
de: "Zurück",
en: "Previous",
};
pub const NEXT: Text = Text {
de: "Weiter",
en: "Next",
};
pub const PER_PAGE: Text = Text {
de: "Pro Seite",
en: "Per page",
};
/// Where a pager stands: "Seite 2 von 5", "Page 2 of 5".
pub fn page_of(current: u64, total: u64, lang: super::super::Lang) -> String {
match lang {
super::super::Lang::De => format!("Seite {current} von {total}"),
super::super::Lang::En => format!("Page {current} of {total}"),
}
}
pub const CRITICAL: Text = Text {
de: "Kritisch",
en: "Critical",
@@ -73,6 +94,19 @@ pub mod common {
de: "In dieser Umgebung nicht verfügbar",
en: "Not available in this environment",
};
#[cfg(test)]
mod pager_tests {
use super::*;
use crate::i18n::Lang;
#[test]
fn the_pager_reads_like_the_language() {
assert_eq!(page_of(2, 5, Lang::De), "Seite 2 von 5");
assert_eq!(page_of(2, 5, Lang::En), "Page 2 of 5");
assert_eq!((PREVIOUS.de, NEXT.de), ("Zurück", "Weiter"));
}
}
}
/// The sidebar.
@@ -688,6 +722,16 @@ pub mod scans {
pub mod targets {
use super::Text;
/// How many targets the selection holds: "1 Prüfobjekt", "12 targets".
pub fn count(total: u64, lang: super::super::Lang) -> String {
match (lang, total) {
(super::super::Lang::De, 1) => "1 Prüfobjekt".to_string(),
(super::super::Lang::De, n) => format!("{n} Prüfobjekte"),
(super::super::Lang::En, 1) => "1 target".to_string(),
(super::super::Lang::En, n) => format!("{n} targets"),
}
}
pub const TITLE: Text = Text {
de: "Prüfobjekte",
en: "Targets",
@@ -962,6 +1006,20 @@ pub mod targets {
de: "Das Nachweispaket konnte nicht erstellt werden",
en: "The evidence pack could not be built",
};
#[cfg(test)]
mod count_tests {
use super::*;
use crate::i18n::Lang;
#[test]
fn the_target_count_reads_like_the_language() {
assert_eq!(count(1, Lang::De), "1 Prüfobjekt");
assert_eq!(count(12, Lang::De), "12 Prüfobjekte");
assert_eq!(count(1, Lang::En), "1 target");
assert_eq!(count(0, Lang::En), "0 targets");
}
}
}
/// Target types and artifact kinds, keyed by their API value.
@@ -307,16 +307,51 @@ pub fn validate_artifact_ref(kind: &str, source_ref: &str) -> Option<String> {
}
}
/// List onboarded targets.
#[server]
pub async fn fetch_targets() -> Result<TargetsResponse, ServerFnError> {
fetch_targets_in(None).await
/// The page size `fetch_targets` reads with: the agent's largest page.
#[cfg(feature = "server")]
const ALL_PAGE_SIZE: u64 = 200;
/// Pages `fetch_targets` reads at most (100,000 targets), so a total that
/// keeps changing cannot keep it reading forever.
#[cfg(feature = "server")]
const MAX_PAGES: u64 = 500;
/// Whether a page was the last one: it came back short, or everything the
/// agent counted has arrived.
#[cfg(any(feature = "server", test))]
fn is_last_page(received: usize, collected: usize, total: Option<u64>, limit: u64) -> bool {
(received as u64) < limit || total.is_some_and(|total| collected as u64 >= total)
}
/// The targets, only those of `project` when given (`?project=`).
/// Every onboarded target, read page by page (the agent pages its list).
#[server]
pub async fn fetch_targets_in(project: Option<String>) -> Result<TargetsResponse, ServerFnError> {
let mut req = super::agent_client::agent_get("/api/v1/targets").await?;
pub async fn fetch_targets() -> Result<TargetsResponse, ServerFnError> {
let mut data = Vec::new();
for page in 1..=MAX_PAGES {
let resp = fetch_targets_page(None, page, ALL_PAGE_SIZE).await?;
let received = resp.data.len();
data.extend(resp.data);
if is_last_page(received, data.len(), resp.total, ALL_PAGE_SIZE) {
break;
}
}
Ok(TargetsResponse {
total: Some(data.len() as u64),
data,
})
}
/// One page of the targets (`page` from 1, `limit` per page), only those of
/// `project` when given; `total` counts every page of that selection.
#[server]
pub async fn fetch_targets_page(
project: Option<String>,
page: u64,
limit: u64,
) -> Result<TargetsResponse, ServerFnError> {
let mut req = super::agent_client::agent_get("/api/v1/targets")
.await?
.query(&[("page", page), ("limit", limit)]);
if let Some(project) = project.filter(|p| !p.is_empty()) {
req = req.query(&[("project", project)]);
}
@@ -582,6 +617,17 @@ mod tests {
}
use super::*;
#[test]
fn reading_every_target_stops_at_a_short_page_or_the_total() {
assert!(!is_last_page(200, 200, Some(450), 200));
assert!(is_last_page(50, 450, Some(450), 200));
// A full last page ends at the total, without asking for an empty one.
assert!(is_last_page(200, 400, Some(400), 200));
// Without a total, a short page is the end.
assert!(!is_last_page(200, 200, None, 200));
assert!(is_last_page(0, 200, None, 200));
}
#[test]
fn an_archive_password_is_missing_until_it_is_set() {
let plain = serde_json::json!({ "kind": "source_archive", "detected": [] });
+78 -10
View File
@@ -11,6 +11,7 @@ use crate::components::cra_bar::CraBar;
use crate::components::demo_targets::DemoTargetsButton;
use crate::components::no_access::use_can_write;
use crate::components::page_header::PageHeader;
use crate::components::pagination::Pagination;
use crate::components::projects::ProjectChips;
use crate::components::scan_runs::status_badge;
use crate::components::toast::{ToastType, Toasts};
@@ -18,7 +19,7 @@ use crate::i18n::texts::{common, kinds, scans as scan_texts, targets as tx};
use crate::i18n::{format_ago, use_lang, Lang};
use crate::infrastructure::auth_check::{go_to_login, is_session_expired};
use crate::infrastructure::evidence::fetch_compliance_summary;
use crate::infrastructure::onboarding::{fetch_targets_in, trigger_target_scan};
use crate::infrastructure::onboarding::{fetch_targets_page, trigger_target_scan};
use crate::infrastructure::projects::{fetch_projects, project_ids_of};
use compliance_core::models::{ScanRun, ScanRunStatus};
@@ -26,6 +27,14 @@ use compliance_core::models::{ScanRun, ScanRunStatus};
#[cfg(feature = "web")]
const REFRESH_MS: u32 = 5_000;
/// The page sizes on offer; the first is the default.
const PAGE_SIZES: [u64; 3] = [20, 50, 100];
/// How many pages `total` targets fill at `page_size` a page (at least one).
fn page_count(total: u64, page_size: u64) -> u64 {
total.div_ceil(page_size.max(1)).max(1)
}
/// The last scan's badge class and label (with the step a running scan is
/// at) and how long ago it was, or `None` before the first scan.
fn last_scan_label(
@@ -73,16 +82,31 @@ pub fn TargetsPage() -> Element {
// The chosen project filter (`None`: every target); the list reloads when
// it changes, since the resource reads it.
let mut project = use_signal(|| Option::<String>::None);
// The agent pages the list; a filter or page-size change starts at page 1.
let mut page = use_signal(|| 1u64);
let mut page_size = use_signal(|| PAGE_SIZES[0]);
let projects = use_resource(fetch_projects);
// A failure keeps its reason, to show it; an expired sign-in goes to the
// login instead.
let mut targets = use_resource(move || async move {
fetch_targets_in(project()).await.map_err(|e| {
if is_session_expired(&e) {
go_to_login();
}
e.to_string()
})
fetch_targets_page(project(), page(), page_size())
.await
.map_err(|e| {
if is_session_expired(&e) {
go_to_login();
}
e.to_string()
})
});
// A page past the end (targets deleted, another tab) moves to the last one.
use_effect(move || {
let last = match &*targets.read() {
Some(Ok(resp)) => page_count(resp.total.unwrap_or(0), page_size()),
_ => return,
};
if page() > last {
page.set(last);
}
});
let summary = use_resource(move || async move { fetch_compliance_summary().await.ok() });
let lang = use_lang()();
@@ -122,6 +146,7 @@ pub fn TargetsPage() -> Element {
onchange: move |e| {
let v = e.value();
project.set((!v.is_empty()).then_some(v));
page.set(1);
},
option { value: "", selected: project().is_none(), {crate::i18n::texts::projects::ALL.get(lang)} }
for p in list {
@@ -148,12 +173,12 @@ pub fn TargetsPage() -> Element {
.and_then(|r| r.counts)
};
match &targets_snapshot {
Some(Ok(resp)) if resp.data.is_empty() && project().is_some() => rsx! {
Some(Ok(resp)) if resp.total == Some(0) && project().is_some() => rsx! {
div { class: "card targets-empty",
p { {crate::i18n::texts::projects::NONE_IN_PROJECT.get(lang)} }
}
},
Some(Ok(resp)) if resp.data.is_empty() => rsx! {
Some(Ok(resp)) if resp.total == Some(0) => rsx! {
div { class: "card targets-empty",
p { {tx::EMPTY.get(lang)} }
div { class: "targets-empty-actions",
@@ -170,7 +195,9 @@ pub fn TargetsPage() -> Element {
p { class: "targets-empty-hint", {tx::DEMO_HINT.get(lang)} }
}
},
Some(Ok(resp)) => rsx! {
Some(Ok(resp)) => {
let total = resp.total.unwrap_or(resp.data.len() as u64);
rsx! {
div { class: "card",
div { class: "table-wrapper",
table { class: "targets-table",
@@ -269,6 +296,34 @@ pub fn TargetsPage() -> Element {
}
}
}
div { class: "targets-pager",
span { class: "targets-total", {tx::count(total, lang)} }
label { class: "project-filter",
span { {common::PER_PAGE.get(lang)} }
select {
onchange: move |e| {
if let Ok(size) = e.value().parse() {
page_size.set(size);
page.set(1);
}
},
for size in PAGE_SIZES {
option {
key: "{size}",
value: "{size}",
selected: page_size() == size,
"{size}"
}
}
}
}
}
Pagination {
current_page: page(),
total_pages: page_count(total, page_size()),
on_page_change: move |p| page.set(p),
}
}
}
},
Some(Err(reason)) => rsx! {
@@ -285,3 +340,16 @@ pub fn TargetsPage() -> Element {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_pages_cover_every_target_and_there_is_always_one() {
assert_eq!(page_count(0, 20), 1);
assert_eq!(page_count(20, 20), 1);
assert_eq!(page_count(21, 20), 2);
assert_eq!(page_count(101, 50), 3);
}
}