PR-10 e PR-11 LogService

This commit is contained in:
Nilton Constantino
2026-01-16 22:54:38 +00:00
parent 5e5b703a56
commit c37b7aca46
14 changed files with 374 additions and 7 deletions
@@ -1,10 +1,12 @@
use crate::fs::{FsBackend, FsState, VirtualFS};
use crate::hardware::{HardwareBridge, InputSignals};
use crate::log::{LogLevel, LogService, LogSource};
use crate::model::{Cartridge, Color, Sample};
use crate::prometeu_os::NativeInterface;
use crate::virtual_machine::{Value, VirtualMachine};
use crate::fs::{VirtualFS, FsBackend, FsState};
use std::sync::Arc;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Instant;
/// PrometeuOS (POS): O firmware/base do sistema.
/// Autoridade máxima do boot, periféricos, execução da PVM e tratamento de falhas.
@@ -25,13 +27,23 @@ pub struct PrometeuOS {
pub fs_state: FsState,
pub open_files: HashMap<u32, String>,
pub next_handle: u32,
// Log Service
pub log_service: LogService,
pub current_app_id: u32,
pub logs_written_this_frame: HashMap<u32, u32>,
boot_time: Instant,
}
impl PrometeuOS {
pub const CYCLES_PER_LOGICAL_FRAME: u64 = 100_000;
pub const SLICE_PER_TICK: u64 = 100_000; // Por enquanto, o mesmo, mas permite granularidade diferente
pub const MAX_LOG_LEN: usize = 256;
pub const MAX_LOGS_PER_FRAME: u32 = 10;
pub fn new() -> Self {
let boot_time = Instant::now();
let mut os = Self {
tick_index: 0,
logical_frame_index: 0,
@@ -45,20 +57,36 @@ impl PrometeuOS {
fs_state: FsState::Unmounted,
open_files: HashMap::new(),
next_handle: 1,
log_service: LogService::new(4096),
current_app_id: 0,
logs_written_this_frame: HashMap::new(),
boot_time,
};
// Inicializa samples básicos (mesma lógica do LogicalHardware)
os.sample_square = Some(Arc::new(Self::create_square_sample(440.0, 0.1)));
os.log(LogLevel::Info, LogSource::Pos, 0, "PrometeuOS starting...".to_string());
os
}
pub fn log(&mut self, level: LogLevel, source: LogSource, tag: u16, msg: String) {
let ts_ms = self.boot_time.elapsed().as_millis() as u64;
let frame = self.logical_frame_index;
self.log_service.log(ts_ms, frame, level, source, tag, msg);
}
pub fn mount_fs(&mut self, backend: Box<dyn FsBackend>) {
self.log(LogLevel::Info, LogSource::Fs, 0, "Attempting to mount filesystem".to_string());
match self.fs.mount(backend) {
Ok(_) => {
self.fs_state = FsState::Mounted;
self.log(LogLevel::Info, LogSource::Fs, 0, "Filesystem mounted successfully".to_string());
}
Err(e) => {
let err_msg = format!("Failed to mount filesystem: {:?}", e);
self.log(LogLevel::Error, LogSource::Fs, 0, err_msg);
self.fs_state = FsState::Error(e);
}
}
@@ -72,6 +100,7 @@ impl PrometeuOS {
fn update_fs(&mut self) {
if self.fs_state == FsState::Mounted {
if !self.fs.is_healthy() {
self.log(LogLevel::Error, LogSource::Fs, 0, "Filesystem became unhealthy, unmounting".to_string());
self.unmount_fs();
}
}
@@ -89,6 +118,13 @@ impl PrometeuOS {
/// Carrega um cartucho na PVM e reseta o estado de execução.
pub fn initialize_vm(&mut self, vm: &mut VirtualMachine, cartridge: &Cartridge) {
vm.initialize(cartridge.program.clone());
// Determina o app_id numérico (hash da string app_id)
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut s = DefaultHasher::new();
cartridge.header.app_id.hash(&mut s);
self.current_app_id = s.finish() as u32;
}
/// Executa um tick do host (60Hz).
@@ -123,7 +159,9 @@ impl PrometeuOS {
}
}
Err(e) => {
return Some(format!("PVM Fault: {:?}", e));
let err_msg = format!("PVM Fault: {:?}", e);
self.log(LogLevel::Error, LogSource::Vm, 0, err_msg.clone());
return Some(err_msg);
}
}
}
@@ -134,10 +172,44 @@ impl PrometeuOS {
fn begin_logical_frame(&mut self, _signals: &InputSignals, hw: &mut dyn HardwareBridge) {
hw.audio_mut().clear_commands();
self.logs_written_this_frame.clear();
}
// Helper para syscalls
fn syscall_log_write(&mut self, level_val: i64, tag: u16, msg: String) -> Result<u64, String> {
let level = match level_val {
0 => LogLevel::Trace,
1 => LogLevel::Debug,
2 => LogLevel::Info,
3 => LogLevel::Warn,
4 => LogLevel::Error,
_ => return Err(format!("Invalid log level: {}", level_val)),
};
let app_id = self.current_app_id;
let count = *self.logs_written_this_frame.get(&app_id).unwrap_or(&0);
if count >= Self::MAX_LOGS_PER_FRAME {
if count == Self::MAX_LOGS_PER_FRAME {
self.logs_written_this_frame.insert(app_id, count + 1);
self.log(LogLevel::Warn, LogSource::App { app_id }, 0, "App exceeded log limit per frame".to_string());
}
return Ok(50);
}
self.logs_written_this_frame.insert(app_id, count + 1);
let mut final_msg = msg;
if final_msg.len() > Self::MAX_LOG_LEN {
final_msg.truncate(Self::MAX_LOG_LEN);
}
self.log(level, LogSource::App { app_id }, tag, final_msg);
Ok(100)
}
pub fn get_color(&self, index: usize, hw: &mut dyn HardwareBridge) -> Color {
if let Some(bank) = hw.gfx().banks[0].as_ref() {
bank.palettes[0][index % 16]
@@ -285,6 +357,75 @@ mod tests {
assert!(cycles_after_tick_2 > cycles_after_tick_1, "VM should have consumed more cycles because FrameSync reset the budget");
}
#[test]
fn test_syscall_log_write_and_rate_limit() {
let mut os = PrometeuOS::new();
let mut vm = VirtualMachine::default();
let mut hw = Hardware::new();
os.current_app_id = 123;
// 1. Teste de log normal
vm.push(Value::Integer(2)); // Info
vm.push(Value::String("Hello Log".to_string()));
let res = os.syscall(0x5001, &mut vm, &mut hw);
assert!(res.is_ok());
let recent = os.log_service.get_recent(1);
assert_eq!(recent[0].msg, "Hello Log");
assert_eq!(recent[0].level, LogLevel::Info);
assert_eq!(recent[0].source, LogSource::App { app_id: 123 });
// 2. Teste de truncamento
let long_msg = "A".repeat(300);
vm.push(Value::Integer(3)); // Warn
vm.push(Value::String(long_msg));
os.syscall(0x5001, &mut vm, &mut hw).unwrap();
let recent = os.log_service.get_recent(1);
assert_eq!(recent[0].msg.len(), 256);
assert!(recent[0].msg.starts_with("AAAAA"));
// 3. Teste de Rate Limit
// Já fizemos 2 logs. O limite é 10.
for i in 0..8 {
vm.push(Value::Integer(2));
vm.push(Value::String(format!("Log {}", i)));
os.syscall(0x5001, &mut vm, &mut hw).unwrap();
}
// O 11º log deve ser ignorado (e deve gerar um aviso do sistema)
vm.push(Value::Integer(2));
vm.push(Value::String("Eleventh log".to_string()));
os.syscall(0x5001, &mut vm, &mut hw).unwrap();
let recent = os.log_service.get_recent(2);
// O último log deve ser o aviso de rate limit (veio depois do 10º log tentado)
assert_eq!(recent[1].msg, "App exceeded log limit per frame");
assert_eq!(recent[1].level, LogLevel::Warn);
// O log "Eleventh log" não deve estar lá
assert_ne!(recent[0].msg, "Eleventh log");
// 4. Teste de reset do rate limit no próximo frame
os.begin_logical_frame(&InputSignals::default(), &mut hw);
vm.push(Value::Integer(2));
vm.push(Value::String("New frame log".to_string()));
os.syscall(0x5001, &mut vm, &mut hw).unwrap();
let recent = os.log_service.get_recent(1);
assert_eq!(recent[0].msg, "New frame log");
// 5. Teste de LOG_WRITE_TAG
vm.push(Value::Integer(2)); // Info
vm.push(Value::Integer(42)); // Tag
vm.push(Value::String("Tagged Log".to_string()));
os.syscall(0x5002, &mut vm, &mut hw).unwrap();
let recent = os.log_service.get_recent(1);
assert_eq!(recent[0].msg, "Tagged Log");
assert_eq!(recent[0].tag, 42);
}
}
impl NativeInterface for PrometeuOS {
@@ -450,6 +591,28 @@ impl NativeInterface for PrometeuOS {
Ok(500)
}
// --- Log Syscalls (0x5000) ---
// LOG_WRITE(level, msg)
0x5001 => {
let msg = match vm.pop()? {
Value::String(s) => s,
_ => return Err("Expected string message".into()),
};
let level = vm.pop_integer()?;
self.syscall_log_write(level, 0, msg)
}
// LOG_WRITE_TAG(level, tag, msg)
0x5002 => {
let msg = match vm.pop()? {
Value::String(s) => s,
_ => return Err("Expected string message".into()),
};
let tag = vm.pop_integer()? as u16;
let level = vm.pop_integer()?;
self.syscall_log_write(level, tag, msg)
}
_ => Err(format!("Unknown syscall: 0x{:08X}", id)),
}
}