Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 62 additions & 1 deletion crates/chunk-cli/src/local/logs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,37 @@ impl Visit for Line {
}
}

/// Parsed components of a JVM log line emitted by [`follow_jvms`].
#[derive(Debug, PartialEq, Eq)]
pub(super) struct JvmLine<'a> {
pub host: &'a str,
pub session: Option<&'a str>,
pub body: &'a str,
}

/// Splits `<short-host> [[session:<id>] ]<body>` into its host prefix, optional session ID, and message body.
pub(super) fn parse_jvm_line(line: &str) -> JvmLine<'_> {
let Some((host, rest)) = line.split_once(' ') else {
return JvmLine { host: "", session: None, body: line };
};
if let Some((session, body)) = strip_session_tag(rest) {
JvmLine { host, session: Some(session), body }
} else {
JvmLine { host, session: None, body: rest }
}
}

fn strip_session_tag(rest: &str) -> Option<(&str, &str)> {
let after_prefix = rest.strip_prefix("[session:")?;
let end = after_prefix.find(']')?;
let id = &after_prefix[..end];
if id.is_empty() || id.len() > 128 || !id.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_')) {
return None;
}
let trailing = &after_prefix[end + 1..];
if trailing.is_empty() { Some((id, "")) } else { trailing.strip_prefix(' ').map(|body| (id, body)) }
}

/// Follows every `<nodes>/*.jvm.log`, skipping output written before the session started.
pub(super) async fn follow_jvms(nodes: PathBuf, reporter: Reporter, stop: CancellationToken) {
let mut offsets = HashMap::new();
Expand All @@ -72,7 +103,8 @@ pub(super) async fn follow_jvms(nodes: PathBuf, reporter: Reporter, stop: Cancel
let offset = offsets.entry(path.clone()).or_insert_with(|| {
if first { std::fs::metadata(&path).map_or(0, |metadata| metadata.len()) } else { 0 }
});
let host = path.file_name().and_then(|name| name.to_str()).unwrap_or_default();
let file = path.file_name().and_then(|name| name.to_str()).unwrap_or_default();
let host = file.strip_suffix(".jvm.log").unwrap_or(file);
for line in read_lines(&path, offset) {
reporter.log(Source::Jvm, format!("{} {line}", &host[..host.len().min(8)]));
}
Expand Down Expand Up @@ -112,3 +144,32 @@ fn read_lines(path: &Path, offset: &mut u64) -> Vec<String> {
*offset += end as u64;
String::from_utf8_lossy(&buffer[..end]).lines().map(str::to_owned).collect()
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn parses_tagged_and_untagged_jvm_lines() {
assert_eq!(
parse_jvm_line("5a9e4aba [session:f47ac10b-58cc] player joined"),
JvmLine { host: "5a9e4aba", session: Some("f47ac10b-58cc"), body: "player joined" }
);
assert_eq!(
parse_jvm_line("5a9e4aba [session:sess_1]"),
JvmLine { host: "5a9e4aba", session: Some("sess_1"), body: "" }
);
assert_eq!(
parse_jvm_line("5a9e4aba JVM started"),
JvmLine { host: "5a9e4aba", session: None, body: "JVM started" }
);
assert_eq!(
parse_jvm_line("5a9e4aba [session:invalid id] hi"),
JvmLine { host: "5a9e4aba", session: None, body: "[session:invalid id] hi" }
);
assert_eq!(
parse_jvm_line("5a9e4aba [session:] hi"),
JvmLine { host: "5a9e4aba", session: None, body: "[session:] hi" }
);
}
}
110 changes: 91 additions & 19 deletions crates/chunk-cli/src/local/tui/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@ use std::{
time::{Duration, Instant},
};

use chunk_proto::sync::v1::Node;
use chunk_proto::sync::v1::{Node, NodePhase, NodeSession};

use super::super::report::{Deployment, Event, Source, Step};
use super::super::{
logs,
report::{Deployment, Event, Source, Step},
};

mod players;

Expand Down Expand Up @@ -45,6 +48,18 @@ pub(super) enum Focus {
Nodes,
}

/// Which JVM log scope is selected in the JVM tab.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(super) enum JvmSelection {
#[default]
All,
Node(String),
Session {
host: String,
session: String,
},
}

pub(super) struct Progress {
pub name: &'static str,
pub state: Step,
Expand Down Expand Up @@ -89,8 +104,8 @@ pub(super) struct Model {
/// Lines scrolled up from the newest output of the visible log.
pub scroll: usize,
pub focus: Focus,
/// Full host identity; None selects the combined JVM output.
pub node: Option<String>,
/// Selected node or nested session; `All` selects the combined JVM output.
pub selection: JvmSelection,
pub show_details: bool,
/// Player ID the players tab has selected; the first match when absent or gone.
pub player: Option<String>,
Expand Down Expand Up @@ -121,7 +136,7 @@ impl Model {
selected: Source::Build.index(),
scroll: 0,
focus: Focus::Logs,
node: None,
selection: JvmSelection::All,
show_details: false,
player: None,
filter: String::new(),
Expand All @@ -136,9 +151,18 @@ impl Model {
Event::Log { source, line } => self.push(source, line),
Event::Deployments(deployments) => {
self.deployments = deployments;
if self.node.is_some() && self.selected_node().is_none() {
self.node = None;
self.scroll = 0;
match &self.selection {
JvmSelection::All => {}
JvmSelection::Node(_) if self.selected_node().is_some() => {}
JvmSelection::Session { .. } if self.selected_session().is_some() => {}
JvmSelection::Session { host, .. } if self.find_node(host).is_some() => {
self.selection = JvmSelection::Node(host.clone());
self.scroll = 0;
}
JvmSelection::Node(_) | JvmSelection::Session { .. } => {
self.selection = JvmSelection::All;
self.scroll = 0;
}
}
}
}
Expand Down Expand Up @@ -224,18 +248,33 @@ impl Model {
}
}

/// Selecting a node immediately previews its logs; row zero is all nodes.
/// Selecting a node or nested session immediately previews its logs; row zero is all nodes.
pub fn move_node(&mut self, offset: isize) {
if !self.on_jvm() {
return;
}
let hosts = self.hosts();
let selected = self.node.as_deref().and_then(|node| hosts.iter().position(|host| *host == node));
let row = selected.map_or(0, |index| index + 1).saturating_add_signed(offset).min(hosts.len());
self.node = row.checked_sub(1).map(|index| hosts[index].to_owned());
let entries = self.jvm_entries();
let current = entries.iter().position(|entry| entry == &self.selection).unwrap_or(0);
let next = current.saturating_add_signed(offset).min(entries.len().saturating_sub(1));
self.selection = entries[next].clone();
self.scroll = 0;
}

pub fn jvm_entries(&self) -> Vec<JvmSelection> {
let mut entries = vec![JvmSelection::All];
for deployment in &self.deployments {
for (host, node) in &deployment.nodes {
entries.push(JvmSelection::Node(host.clone()));
if node.phase() != NodePhase::Stopped {
for session in &node.sessions {
entries.push(JvmSelection::Session { host: host.clone(), session: session.id.clone() });
}
}
}
}
entries
}

pub fn open_node(&mut self) {
self.focus = Focus::Logs;
}
Expand All @@ -255,17 +294,41 @@ impl Model {
self.deployments.iter().flat_map(|deployment| &deployment.nodes).map(|(host, _)| host.as_str()).collect()
}

pub fn selected_node(&self) -> Option<(&Deployment, &(String, Node))> {
let host = self.node.as_deref()?;
fn find_node(&self, host: &str) -> Option<(&Deployment, &(String, Node))> {
self.deployments
.iter()
.find_map(|deployment| deployment.nodes.iter().find(|(id, _)| id == host).map(|node| (deployment, node)))
}

pub fn selected_node(&self) -> Option<(&Deployment, &(String, Node))> {
let JvmSelection::Node(host) = &self.selection else { return None };
self.find_node(host)
}

pub fn selected_session(&self) -> Option<(&Deployment, &(String, Node), &NodeSession)> {
let JvmSelection::Session { host, session } = &self.selection else { return None };
let (deployment, node) = self.find_node(host)?;
if node.1.phase() == NodePhase::Stopped {
return None;
}
let open = node.1.sessions.iter().find(|candidate| candidate.id == *session)?;
Some((deployment, node, open))
}

pub fn sessions(&self) -> usize {
self.deployments
.iter()
.flat_map(|deployment| &deployment.nodes)
.filter(|(_, node)| node.phase() != NodePhase::Stopped)
.map(|(_, node)| node.sessions.len())
.sum()
}

pub fn players(&self) -> u32 {
self.deployments
.iter()
.flat_map(|deployment| &deployment.nodes)
.filter(|(_, node)| node.phase() != NodePhase::Stopped)
.filter_map(|(_, node)| node.health.as_ref())
.map(|health| health.players)
.sum()
Expand All @@ -285,10 +348,19 @@ impl Model {
}

fn shows(&self, line: &str) -> bool {
!self.on_jvm()
|| self.node.as_ref().is_none_or(|host| {
line.strip_prefix(&host[..host.len().min(8)]).is_some_and(|rest| rest.starts_with(' '))
})
if !self.on_jvm() {
return true;
}
match &self.selection {
JvmSelection::All => true,
// Node views keep untagged JVM-wide lines (startup, GC) alongside every session on that host.
JvmSelection::Node(host) => logs::parse_jvm_line(line).host == &host[..host.len().min(8)],
// Session views show only lines tagged with that session; untagged JVM lines stay at the node level.
JvmSelection::Session { host, session } => {
let parsed = logs::parse_jvm_line(line);
parsed.host == &host[..host.len().min(8)] && parsed.session == Some(session.as_str())
}
}
}
}

Expand Down
88 changes: 84 additions & 4 deletions crates/chunk-cli/src/local/tui/model/tests.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use chunk_proto::sync::v1::{Node, OperatorPlayer, SessionDemand};
use chunk_proto::sync::v1::{JvmSessionPhase, Node, NodePhase, NodeSession, OperatorPlayer, SessionDemand};

use crate::local::Command;

Expand Down Expand Up @@ -57,12 +57,12 @@ fn node_selection_previews_logs_and_survives_refreshes_and_tab_changes() {
assert_eq!(model.focus, Focus::Nodes);
assert_eq!(model.visible().len(), 1);
model.move_node(-1);
assert!(model.node.is_none());
assert_eq!(model.selection, JvmSelection::All);
assert_eq!(model.visible().len(), 3);

model.move_node(1);
nodes(&mut model, &["aaaaaaaa-1111"]);
assert!(model.node.is_none());
assert_eq!(model.selection, JvmSelection::All);
assert_eq!(model.scroll, 0);
}

Expand All @@ -79,7 +79,7 @@ fn failed_reload_preserves_the_dashboard_and_selected_node() {
state: Step::Failed("compile failed\nthe previous release keeps serving".into()),
});
assert!(model.ready());
assert_eq!(model.node.as_deref(), Some("aaaaaaaa-1111"));
assert_eq!(model.selection, JvmSelection::Node("aaaaaaaa-1111".into()));
assert!(matches!(model.step("Compile").unwrap().state, Step::Failed(_)));
assert!(model.step("Compile").unwrap().started.is_none());
model.apply(Event::Step { name: "Reload", state: Step::Running("Lobby.kt".into()) });
Expand Down Expand Up @@ -178,3 +178,83 @@ fn search_keeps_a_matching_selection_and_the_move_form_targets_it() {
model.cancel();
assert!(model.filter.is_empty() && model.input.is_none());
}

#[test]
fn session_selection_filters_tagged_lines_keeps_untagged_at_node_and_falls_back_to_parent() {
let session = |id: &str, key: &str, players: u32| NodeSession {
id: id.into(),
session_type: "arena/default".into(),
key: key.into(),
players,
phase: JvmSessionPhase::Ready.into(),
};
let mut model = Model::new();
ready(&mut model);
model.apply(Event::Deployments(vec![Deployment {
id: "release".into(),
state: "current".into(),
nodes: vec![
(
"aaaaaaaa-1111".into(),
Node {
app: "arena".into(),
phase: NodePhase::Online.into(),
sessions: vec![session("sess-1111-aaaa", "duel-1", 2), session("sess-2222-bbbb", "duel-2", 1)],
..Default::default()
},
),
(
"bbbbbbbb-2222".into(),
Node {
app: "lobby".into(),
phase: NodePhase::Stopped.into(),
sessions: vec![session("stale-session", "main", 5)],
..Default::default()
},
),
],
players: Vec::new(),
destinations: Vec::new(),
}]));

assert_eq!(model.sessions(), 2);
log(&mut model, Source::Jvm, "aaaaaaaa JVM started");
log(&mut model, Source::Jvm, "aaaaaaaa [session:sess-1111-aaaa] round 1");
log(&mut model, Source::Jvm, "aaaaaaaa [session:sess-2222-bbbb] round 2");
log(&mut model, Source::Jvm, "bbbbbbbb lobby stopped");

// All nodes shows everything.
assert_eq!(model.visible().len(), 4);

// Row 1 selects node aaaaaaaa: includes untagged startup + both sessions.
model.move_node(1);
assert_eq!(model.selection, JvmSelection::Node("aaaaaaaa-1111".into()));
assert_eq!(model.visible().len(), 3);

// Row 2 selects sess-1111-aaaa: only lines tagged with that session (untagged stays at node level).
model.move_node(1);
assert_eq!(
model.selection,
JvmSelection::Session { host: "aaaaaaaa-1111".into(), session: "sess-1111-aaaa".into() }
);
assert_eq!(model.visible(), ["aaaaaaaa [session:sess-1111-aaaa] round 1"]);

// When the selected session ends, selection falls back to its parent node.
model.apply(Event::Deployments(vec![Deployment {
id: "release".into(),
state: "current".into(),
nodes: vec![(
"aaaaaaaa-1111".into(),
Node {
app: "arena".into(),
phase: NodePhase::Online.into(),
sessions: vec![session("sess-2222-bbbb", "duel-2", 1)],
..Default::default()
},
)],
players: Vec::new(),
destinations: Vec::new(),
}]));
assert_eq!(model.selection, JvmSelection::Node("aaaaaaaa-1111".into()));
assert_eq!(model.visible().len(), 3);
}
Loading