feat(networks): add host/application counts columns and fix Actions header

Adds NetworkWithCounts presentation model and get_networks_with_counts()
server function using a single SQL query with correlated subqueries.
Networks table now shows host count, application count, and has the
Actions column header properly right-aligned to match the Delete button.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-15 23:23:12 +02:00
parent 3ee39b96bb
commit 5b1f30fe24
2 changed files with 66 additions and 4 deletions

View File

@@ -1,9 +1,23 @@
// api/networks.rs — Server functions for networks
use leptos::prelude::*;
use serde::{Deserialize, Serialize};
use crate::models::Network;
// Network row augmented with pre-computed counts.
// Defined here (not in models.rs) because it is a presentation model
// specific to the Networks page, not a pure domain entity.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct NetworkWithCounts {
pub id: i64,
pub cidr: String,
/// Number of hosts whose IP falls within this network's CIDR range.
pub host_count: i64,
/// Number of distinct applications linked via ports open on hosts in this network.
pub application_count: i64,
}
// ─── Queries ──────────────────────────────────────────────────────────────────
/// Returns all networks from the database.
@@ -26,6 +40,50 @@ pub async fn get_networks() -> Result<Vec<Network>, ServerFnError> {
.map_err(|e| ServerFnError::new(e.to_string()))
}
/// Returns all networks enriched with host and application counts.
///
/// A single SQL query fetches everything at once using correlated subqueries,
/// avoiding N+1 round-trips regardless of the number of networks.
///
/// `application_count` = distinct applications whose registered ports appear
/// among the ports open on hosts in each network (via host_ports → application_ports).
#[server]
pub async fn get_networks_with_counts() -> Result<Vec<NetworkWithCounts>, ServerFnError> {
use sqlx::{AnyPool, Row};
let pool = use_context::<AnyPool>()
.ok_or_else(|| ServerFnError::new("Database pool not found in context"))?;
let rows = sqlx::query(
"SELECT
n.id,
n.cidr,
(SELECT COUNT(*) FROM hosts WHERE network_id = n.id) AS host_count,
(SELECT COUNT(DISTINCT ap.application_id)
FROM hosts h
JOIN host_ports hp ON hp.host_id = h.id
JOIN application_ports ap ON ap.port_number = hp.port_number
WHERE h.network_id = n.id) AS application_count
FROM networks n
ORDER BY n.id",
)
.fetch_all(&pool)
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
let networks = rows
.into_iter()
.map(|row| NetworkWithCounts {
id: row.get("id"),
cidr: row.get("cidr"),
host_count: row.get("host_count"),
application_count: row.get("application_count"),
})
.collect();
Ok(networks)
}
// ─── Mutations ────────────────────────────────────────────────────────────────
/// Creates a new network with the given CIDR block.