added comments extensively

This commit is contained in:
2026-03-24 13:40:18 +00:00
parent 9ba2aab1a5
commit 075fe8526c
10 changed files with 446 additions and 104 deletions
+42 -14
View File
@@ -5,15 +5,27 @@ use prometeu_core::debugger_protocol::*;
use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
/// Host-side implementation of the PROMETEU DevTools Protocol.
///
/// This component acts as a TCP server that allows external tools (like the
/// Prometeu Debugger) to observe and control the execution of the virtual machine.
///
/// Communication is based on JSONL (JSON lines) over TCP.
pub struct HostDebugger {
/// If true, the VM will not start execution until a 'start' command is received.
pub waiting_for_start: bool,
/// The TCP listener for incoming debugger connections.
pub(crate) listener: Option<TcpListener>,
/// The currently active connection to a debugger client.
pub(crate) stream: Option<TcpStream>,
/// Sequence tracker to ensure logs are sent only once.
last_log_seq: u64,
/// Frame tracker to send telemetry snapshots periodically.
last_telemetry_frame: u64,
}
impl HostDebugger {
/// Creates a new debugger interface in an idle state.
pub fn new() -> Self {
Self {
waiting_for_start: false,
@@ -24,17 +36,21 @@ impl HostDebugger {
}
}
/// Configures the debugger based on the boot target.
/// If debug mode is enabled, it binds to the specified TCP port.
pub fn setup_boot_target(&mut self, boot_target: &BootTarget, firmware: &mut Firmware) {
if let BootTarget::Cartridge { path, debug: true, debug_port } = boot_target {
self.waiting_for_start = true;
// Pre-loads cartridge information for the handshake
// Pre-load cartridge metadata so the Handshake message can contain
// valid information about the App being debugged.
if let Ok(cartridge) = CartridgeLoader::load(path) {
firmware.os.initialize_vm(&mut firmware.vm, &cartridge);
}
match TcpListener::bind(format!("127.0.0.1:{}", debug_port)) {
Ok(listener) => {
// Set listener to non-blocking so it doesn't halt the main loop.
listener.set_nonblocking(true).expect("Cannot set non-blocking");
self.listener = Some(listener);
println!("[Debugger] Listening for start command on port {}...", debug_port);
@@ -48,6 +64,7 @@ impl HostDebugger {
}
}
/// Sends a structured response to the connected debugger client.
fn send_response(&mut self, resp: DebugResponse) {
if let Some(stream) = &mut self.stream {
if let Ok(json) = serde_json::to_string(&resp) {
@@ -57,6 +74,7 @@ impl HostDebugger {
}
}
/// Sends an asynchronous event to the connected debugger client.
fn send_event(&mut self, event: DebugEvent) {
if let Some(stream) = &mut self.stream {
if let Ok(json) = serde_json::to_string(&event) {
@@ -66,16 +84,20 @@ impl HostDebugger {
}
}
/// Main maintenance method called by the HostRunner every iteration.
/// It handles new connections and processes incoming commands.
pub fn check_commands(&mut self, firmware: &mut Firmware, hardware: &mut Hardware) {
// 1. Accept new client connections.
if let Some(listener) = &self.listener {
if let Ok((stream, _addr)) = listener.accept() {
// Currently, only one debugger client is supported at a time.
if self.stream.is_none() {
println!("[Debugger] Connection received!");
stream.set_nonblocking(true).expect("Cannot set non-blocking on stream");
self.stream = Some(stream);
// Send Handshake
// Immediately send the Handshake message to identify the Runtime and App.
let handshake = DebugResponse::Handshake {
protocol_version: DEVTOOLS_PROTOCOL_VERSION,
runtime_version: "0.1".to_string(),
@@ -93,33 +115,35 @@ impl HostDebugger {
}
}
// 2. Read and process pending commands from the network stream.
if let Some(mut stream) = self.stream.take() {
let mut buf = [0u8; 4096];
match stream.read(&mut buf) {
Ok(0) => {
// TCP socket closed by the client.
println!("[Debugger] Connection closed by remote.");
self.stream = None;
// Resume VM execution if it was paused waiting for the debugger.
firmware.os.paused = false;
self.waiting_for_start = false;
}
Ok(n) => {
let data = &buf[..n];
// Process multiple commands if there's \n
let msg = String::from_utf8_lossy(data);
self.stream = Some(stream); // Put it back before processing commands
self.stream = Some(stream);
// Support multiple JSON messages in a single TCP packet.
for line in msg.lines() {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
if trimmed.is_empty() { continue; }
if let Ok(cmd) = serde_json::from_str::<DebugCommand>(trimmed) {
self.handle_command(cmd, firmware, hardware);
}
}
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
// No data available right now, continue.
self.stream = Some(stream);
}
Err(e) => {
@@ -131,12 +155,13 @@ impl HostDebugger {
}
}
// Streaming de eventos
// 3. Push events (logs, telemetry) to the client.
if self.stream.is_some() {
self.stream_events(firmware);
}
}
/// Dispatches a specific DebugCommand to the system components.
fn handle_command(&mut self, cmd: DebugCommand, firmware: &mut Firmware, hardware: &mut Hardware) {
match cmd {
DebugCommand::Ok | DebugCommand::Start => {
@@ -153,15 +178,17 @@ impl HostDebugger {
firmware.os.paused = false;
}
DebugCommand::Step => {
// Execute exactly one instruction and keep paused.
firmware.os.paused = true;
// Executes an instruction immediately
let _ = firmware.os.debug_step_instruction(&mut firmware.vm, hardware);
}
DebugCommand::StepFrame => {
// Execute until the end of the current logical frame.
firmware.os.paused = false;
firmware.os.debug_step_request = true;
}
DebugCommand::GetState => {
// Return detailed VM register and stack state.
let stack_top = firmware.vm.operand_stack.iter()
.rev().take(10).cloned().collect();
@@ -186,13 +213,14 @@ impl HostDebugger {
}
}
/// Scans the system for new information to push to the debugger client.
fn stream_events(&mut self, firmware: &mut Firmware) {
// Logs
// 1. Process and send new log entries.
let new_events = firmware.os.log_service.get_after(self.last_log_seq);
for event in new_events {
self.last_log_seq = event.seq;
// Check if it's a breakpoint hit via tag
// Map specific internal log tags to protocol events.
if event.tag == 0xDEB1 {
self.send_event(DebugEvent::BreakpointHit {
pc: firmware.vm.pc,
@@ -200,7 +228,7 @@ impl HostDebugger {
});
}
// Certification via Tags 0xCA01-0xCA03
// Map Certification tags (0xCA01-0xCA03) to 'Cert' protocol events.
if event.tag >= 0xCA01 && event.tag <= 0xCA03 {
let rule = match event.tag {
0xCA01 => "cycles_budget",
@@ -211,7 +239,7 @@ impl HostDebugger {
self.send_event(DebugEvent::Cert {
rule,
used: 0, // Simplified, detailed information is in the log message
used: 0,
limit: 0,
frame_index: firmware.os.logical_frame_index,
});
@@ -224,7 +252,7 @@ impl HostDebugger {
});
}
// Telemetria (a cada novo frame)
// 2. Send telemetry snapshots at the completion of every frame.
let current_frame = firmware.os.logical_frame_index;
if current_frame > self.last_telemetry_frame {
let tel = &firmware.os.telemetry_last;
+47 -8
View File
@@ -18,36 +18,62 @@ use winit::window::{Window, WindowAttributes, WindowId};
use prometeu_core::telemetry::CertificationConfig;
/// The Desktop implementation of the PROMETEU Runtime.
///
/// This struct acts as the physical "chassis" of the virtual console. It is
/// responsible for:
/// - Creating and managing the OS window (via `winit`).
/// - Initializing the GPU-accelerated framebuffer (via `pixels`).
/// - Handling real keyboard/gamepad events and converting them to virtual signals.
/// - Providing a high-fidelity audio backend (via `cpal`).
/// - Implementing the DevTools Protocol for remote debugging.
/// - Maintaining a deterministic 60Hz timing loop.
pub struct HostRunner {
/// The OS window handle.
window: Option<&'static Window>,
/// The pixel buffer interface for rendering to the GPU.
pixels: Option<Pixels<'static>>,
/// The instance of the virtual hardware peripherals.
hardware: Hardware,
/// The instance of the system firmware and OS logic.
firmware: Firmware,
/// Helper to collect and normalize input signals.
input: HostInputHandler,
/// Root path for the virtual sandbox filesystem.
fs_root: Option<String>,
/// Sink for system and application logs (prints to console).
log_sink: HostConsoleSink,
/// Target duration for a single frame (nominally 16.66ms for 60Hz).
frame_target_dt: Duration,
/// Last recorded wall-clock time to calculate deltas.
last_frame_time: Instant,
/// Time accumulator used to guarantee exact 60Hz logic updates.
accumulator: Duration,
/// Performance metrics collector.
stats: HostStats,
/// Remote debugger interface.
debugger: HostDebugger,
/// Flag to enable/disable the technical telemetry display.
overlay_enabled: bool,
/// The physical audio driver.
audio: HostAudio,
}
impl HostRunner {
/// Configures the boot target (Hub or specific Cartridge).
pub(crate) fn set_boot_target(&mut self, boot_target: BootTarget) {
self.firmware.boot_target = boot_target.clone();
self.debugger.setup_boot_target(&boot_target, &mut self.firmware);
}
/// Creates a new desktop runner instance.
pub(crate) fn new(fs_root: Option<String>, cap_config: Option<CertificationConfig>) -> Self {
let target_fps = 60;
@@ -203,10 +229,13 @@ impl ApplicationHandler for HostRunner {
}
}
/// Called by `winit` when the application is idle and ready to perform updates.
/// This is where the core execution loop lives.
fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
// 1. Process pending debug commands from the network.
self.debugger.check_commands(&mut self.firmware, &mut self.hardware);
// Updates Filesystem state in OS (specific to prometeu-runtime-desktop)
// 2. Maintain filesystem connection if it was lost (e.g., directory removed).
if let Some(root) = &self.fs_root {
use prometeu_core::fs::FsState;
if matches!(self.firmware.os.fs_state, FsState::Unmounted | FsState::Error(_)) {
@@ -217,10 +246,15 @@ impl ApplicationHandler for HostRunner {
}
}
// 3. Timing Management (The heart of determinism).
// We measure the elapsed time since the last iteration and add it to an
// accumulator. We then execute exactly as many 60Hz slices as the
// accumulator allows.
let now = Instant::now();
let mut frame_delta = now.duration_since(self.last_frame_time);
// Limiter to avoid the "death spiral" if the OS freezes (max 100ms per loop)
// Safety cap: if the OS freezes or we fall behind too much, we don't try
// to catch up indefinitely (avoiding the "death spiral").
if frame_delta > Duration::from_millis(100) {
frame_delta = Duration::from_millis(100);
}
@@ -228,24 +262,27 @@ impl ApplicationHandler for HostRunner {
self.last_frame_time = now;
self.accumulator += frame_delta;
// 🔥 The heart of determinism: consumes time in exact 60Hz slices
// 🔥 Logic Update Loop: consumes time in exact 60Hz (16.66ms) slices.
while self.accumulator >= self.frame_target_dt {
// Unless the debugger is waiting for a 'start' command, advance the system.
if !self.debugger.waiting_for_start {
self.firmware.step_frame(&self.input.signals, &mut self.hardware);
}
// Sync virtual audio commands to the physical mixer.
self.audio.send_commands(&mut self.hardware.audio.commands);
self.accumulator -= self.frame_target_dt;
self.stats.record_frame();
}
// 4. Feedback and Synchronization.
self.audio.update_stats(&mut self.stats);
// Updates statistics every 1 real second
// Update technical statistics displayed in the window title.
self.stats.update(now, self.window, &self.hardware, &self.firmware);
// Process system logs
// Synchronize system logs to the host console.
let last_seq = self.log_sink.last_seq().unwrap_or(u64::MAX);
let new_events = if last_seq == u64::MAX {
self.firmware.os.log_service.get_recent(4096)
@@ -254,13 +291,15 @@ impl ApplicationHandler for HostRunner {
};
self.log_sink.process_events(new_events);
// Telemetry Overlay
// 5. Rendering the Telemetry Overlay (if enabled).
if self.overlay_enabled {
self.hardware.gfx.present(); // Bring front to back to draw over
// We temporarily swap buffers to draw over the current image.
self.hardware.gfx.present();
self.display_dbg_overlay();
self.hardware.gfx.present(); // Return to front with overlay applied
self.hardware.gfx.present();
}
// Finally, request a window redraw to present the new pixels.
self.request_redraw();
}
}