feat(app): M5 step 2, service control and the dashboard data
- control: one Controller starts, stops and restarts the services (stopped, starting, running, stopping, failed); a failed start leaves nothing running and keeps its error with secrets masked. The app binary uses it. - dashboard: built from the core's events alone: the bot's tag, the voice channel, live captions (screen only, cleared on leaving or stopping), the last 20 voice answers split into stages with medians (matched by the new AnswerAsked event), and missed requests without text. - system: memory in use and per NVIDIA GPU its use and VRAM (nvidia-smi). - DiscordCore::voice_members, WorkerClient::hello, the conversation's missed requests shared with the dashboard. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
321
app/src/control.rs
Normal file
321
app/src/control.rs
Normal file
@@ -0,0 +1,321 @@
|
||||
//! Starting and stopping the services, and the dashboard snapshot (`app/src/admin.spec.md`,
|
||||
//! "Service control" and "Dashboard data").
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use serde_json::{json, Value};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::dashboard::Dashboard;
|
||||
use crate::discord::CoreEvent;
|
||||
use crate::system::Usage;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum State {
|
||||
Stopped,
|
||||
Starting,
|
||||
Running,
|
||||
Stopping,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// The running services as the controller sees them.
|
||||
#[async_trait]
|
||||
pub trait Running: Send + Sync + 'static {
|
||||
async fn stop(&self);
|
||||
/// Worker, voice channel members and missed requests, for the snapshot.
|
||||
fn status(&self, now: Instant) -> Value;
|
||||
}
|
||||
|
||||
/// What starts the services (the real ones, or a fake in tests).
|
||||
#[async_trait]
|
||||
pub trait Host: Send + Sync + 'static {
|
||||
async fn start(&self) -> Result<(Arc<dyn Running>, mpsc::UnboundedReceiver<CoreEvent>), String>;
|
||||
/// Stored secrets, masked in error messages.
|
||||
fn secrets(&self) -> Vec<String>;
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
state: State,
|
||||
error: Option<String>,
|
||||
running: Option<Arc<dyn Running>>,
|
||||
}
|
||||
|
||||
pub struct Controller {
|
||||
host: Box<dyn Host>,
|
||||
inner: Mutex<Inner>,
|
||||
dashboard: Arc<Mutex<Dashboard>>,
|
||||
usage: tokio::sync::Mutex<Option<(Instant, Usage)>>,
|
||||
}
|
||||
|
||||
impl Controller {
|
||||
pub fn new(host: impl Host) -> Arc<Self> {
|
||||
Arc::new(Self { host: Box::new(host), inner: Mutex::new(Inner { state: State::Stopped, error: None, running: None }),
|
||||
dashboard: Arc::default(), usage: tokio::sync::Mutex::new(None) })
|
||||
}
|
||||
|
||||
pub fn state(&self) -> State {
|
||||
self.inner.lock().unwrap().state
|
||||
}
|
||||
|
||||
/// Start from stopped or failed; a failed start leaves nothing running.
|
||||
pub async fn start(&self) -> Result<(), String> {
|
||||
{
|
||||
let mut i = self.inner.lock().unwrap();
|
||||
if !matches!(i.state, State::Stopped | State::Failed) {
|
||||
return Err(format!("cannot start while {:?}", i.state).to_lowercase());
|
||||
}
|
||||
i.state = State::Starting;
|
||||
i.error = None;
|
||||
}
|
||||
crate::info_log!("app", "starting the services");
|
||||
match self.host.start().await {
|
||||
Ok((running, mut events)) => {
|
||||
let dash = self.dashboard.clone();
|
||||
tokio::spawn(async move {
|
||||
while let Some(ev) = events.recv().await {
|
||||
dash.lock().unwrap().on_event(&ev, Instant::now());
|
||||
}
|
||||
});
|
||||
let mut i = self.inner.lock().unwrap();
|
||||
i.state = State::Running;
|
||||
i.running = Some(running);
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
let e = crate::logs::redact(&e, &self.host.secrets());
|
||||
crate::error_log!("app", "the services did not start: {e}");
|
||||
let mut i = self.inner.lock().unwrap();
|
||||
i.state = State::Failed;
|
||||
i.error = Some(e.clone());
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stop from running; what was said is forgotten.
|
||||
pub async fn stop(&self) -> Result<(), String> {
|
||||
let running = {
|
||||
let mut i = self.inner.lock().unwrap();
|
||||
if i.state != State::Running {
|
||||
return Err(format!("cannot stop while {:?}", i.state).to_lowercase());
|
||||
}
|
||||
i.state = State::Stopping;
|
||||
i.running.take()
|
||||
};
|
||||
if let Some(r) = running {
|
||||
r.stop().await;
|
||||
}
|
||||
self.dashboard.lock().unwrap().clear();
|
||||
self.inner.lock().unwrap().state = State::Stopped;
|
||||
crate::info_log!("app", "services stopped");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn restart(&self) -> Result<(), String> {
|
||||
if self.state() == State::Running {
|
||||
self.stop().await?;
|
||||
}
|
||||
self.start().await
|
||||
}
|
||||
|
||||
/// Everything the dashboard shows.
|
||||
pub async fn snapshot(&self) -> Value {
|
||||
let now = Instant::now();
|
||||
let (state, error, running) = {
|
||||
let i = self.inner.lock().unwrap();
|
||||
(i.state, i.error.clone(), i.running.clone())
|
||||
};
|
||||
let status = running.map(|r| r.status(now)).unwrap_or_else(|| json!({"worker": null, "voiceMembers": [],
|
||||
"missed": []}));
|
||||
let mut view = self.dashboard.lock().unwrap().view(&[], now);
|
||||
view["missed"] = status["missed"].clone();
|
||||
view["worker"] = status["worker"].clone();
|
||||
view["voiceMembers"] = status["voiceMembers"].clone();
|
||||
view["state"] = json!(state);
|
||||
view["error"] = json!(error);
|
||||
view["system"] = json!(self.system().await);
|
||||
view["performance"] = Value::Null; // game detection comes in M7
|
||||
view
|
||||
}
|
||||
|
||||
/// Memory and GPU use, sampled at most once a second.
|
||||
async fn system(&self) -> Usage {
|
||||
let mut cache = self.usage.lock().await;
|
||||
if let Some((at, u)) = cache.as_ref() {
|
||||
if at.elapsed() < Duration::from_secs(1) {
|
||||
return u.clone();
|
||||
}
|
||||
}
|
||||
let u = crate::system::usage().await;
|
||||
*cache = Some((Instant::now(), u.clone()));
|
||||
u
|
||||
}
|
||||
}
|
||||
|
||||
/// The real services from a data folder.
|
||||
pub struct ServicesHost {
|
||||
pub data_dir: PathBuf,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Host for ServicesHost {
|
||||
async fn start(&self) -> Result<(Arc<dyn Running>, mpsc::UnboundedReceiver<CoreEvent>), String> {
|
||||
let mut s = crate::services::start_services(&self.data_dir).await.map_err(|e| e.to_string())?;
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
let mut events = std::mem::replace(&mut s.events, mpsc::unbounded_channel().1);
|
||||
tokio::spawn(async move {
|
||||
while let Some(e) = events.recv().await {
|
||||
if tx.send(e).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok((Arc::new(s), rx))
|
||||
}
|
||||
|
||||
fn secrets(&self) -> Vec<String> {
|
||||
crate::secrets::Secrets::new(&self.data_dir.join("config").join("secrets.dat")).values()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Running for crate::services::Services {
|
||||
async fn stop(&self) {
|
||||
crate::services::Services::stop(self).await;
|
||||
}
|
||||
|
||||
fn status(&self, now: Instant) -> Value {
|
||||
let hello = self.worker.hello();
|
||||
let missed: Vec<_> = self.missed.lock().unwrap().iter().cloned().collect();
|
||||
json!({
|
||||
"worker": {"connected": hello.is_some(), "sttReady": hello.as_ref().map(|h| h.stt_ready),
|
||||
"ttsReady": hello.as_ref().map(|h| h.tts_ready), "restarts": self.worker_process.restarts()},
|
||||
"voiceMembers": self.core.voice_members().into_iter()
|
||||
.map(|(id, name)| json!({"id": id.to_string(), "name": name})).collect::<Vec<_>>(),
|
||||
"missed": crate::dashboard::missed_view(&missed, now),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Counts {
|
||||
starts: AtomicU32,
|
||||
stops: AtomicU32,
|
||||
}
|
||||
|
||||
struct FakeRunning(Arc<Counts>);
|
||||
#[async_trait]
|
||||
impl Running for FakeRunning {
|
||||
async fn stop(&self) {
|
||||
self.0.stops.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
fn status(&self, _: Instant) -> Value {
|
||||
json!({"worker": {"connected": true}, "voiceMembers": [{"id": "11", "name": "민수"}], "missed": []})
|
||||
}
|
||||
}
|
||||
|
||||
struct FakeHost {
|
||||
counts: Arc<Counts>,
|
||||
fail_first: AtomicU32,
|
||||
events: Mutex<Option<mpsc::UnboundedSender<CoreEvent>>>,
|
||||
}
|
||||
#[async_trait]
|
||||
impl Host for FakeHost {
|
||||
async fn start(&self) -> Result<(Arc<dyn Running>, mpsc::UnboundedReceiver<CoreEvent>), String> {
|
||||
self.counts.starts.fetch_add(1, Ordering::SeqCst);
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
if self.fail_first.load(Ordering::SeqCst) > 0 {
|
||||
self.fail_first.fetch_sub(1, Ordering::SeqCst);
|
||||
return Err("login failed for token Mt0kenSecretValue".into());
|
||||
}
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
*self.events.lock().unwrap() = Some(tx);
|
||||
Ok((Arc::new(FakeRunning(self.counts.clone())), rx))
|
||||
}
|
||||
fn secrets(&self) -> Vec<String> {
|
||||
vec!["Mt0kenSecretValue".into()]
|
||||
}
|
||||
}
|
||||
|
||||
fn controller(fail_first: u32) -> (Arc<Controller>, Arc<Counts>, Arc<FakeHost>) {
|
||||
let counts = Arc::new(Counts::default());
|
||||
let host = Arc::new(FakeHost { counts: counts.clone(), fail_first: AtomicU32::new(fail_first),
|
||||
events: Mutex::new(None) });
|
||||
struct Shared(Arc<FakeHost>);
|
||||
#[async_trait]
|
||||
impl Host for Shared {
|
||||
async fn start(&self) -> Result<(Arc<dyn Running>, mpsc::UnboundedReceiver<CoreEvent>), String> {
|
||||
self.0.start().await
|
||||
}
|
||||
fn secrets(&self) -> Vec<String> {
|
||||
self.0.secrets()
|
||||
}
|
||||
}
|
||||
(Controller::new(Shared(host.clone())), counts, host)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn start_and_stop_follow_the_state_rules() {
|
||||
let (c, counts, _) = controller(0);
|
||||
assert!(c.stop().await.is_err(), "nothing to stop");
|
||||
let c2 = c.clone();
|
||||
let first = tokio::spawn(async move { c2.start().await });
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
assert_eq!(c.state(), State::Starting);
|
||||
assert!(c.start().await.unwrap_err().contains("starting"), "one start at a time");
|
||||
first.await.unwrap().unwrap();
|
||||
assert_eq!(c.state(), State::Running);
|
||||
assert!(c.start().await.is_err());
|
||||
c.restart().await.unwrap();
|
||||
assert_eq!((counts.starts.load(Ordering::SeqCst), counts.stops.load(Ordering::SeqCst)), (2, 1));
|
||||
c.stop().await.unwrap();
|
||||
assert_eq!(c.state(), State::Stopped);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_start_is_reported_masked_and_can_be_retried() {
|
||||
let (c, counts, _) = controller(1);
|
||||
let e = c.start().await.unwrap_err();
|
||||
assert_eq!(e, "login failed for token [비밀값]");
|
||||
let snap = c.snapshot().await;
|
||||
assert_eq!((snap["state"].clone(), snap["error"].clone()), (json!("failed"), json!(e)));
|
||||
c.start().await.unwrap();
|
||||
assert_eq!(c.state(), State::Running);
|
||||
assert_eq!(counts.stops.load(Ordering::SeqCst), 0, "a failed start leaves nothing to stop");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_snapshot_carries_the_events_and_stopping_forgets_what_was_said() {
|
||||
let (c, _, host) = controller(0);
|
||||
c.start().await.unwrap();
|
||||
let tx = host.events.lock().unwrap().clone().unwrap();
|
||||
tx.send(CoreEvent::Ready { user_id: 1, tag: "Jarvis#0001".into() }).unwrap();
|
||||
tx.send(CoreEvent::Joined { guild_id: 1, channel_id: 77 }).unwrap();
|
||||
tx.send(CoreEvent::Partial(crate::discord::Heard { speaker_id: 11, speaker_name: "민수".into(), utt: 1 },
|
||||
"자비스 안녕".into())).unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
let s = c.snapshot().await;
|
||||
assert_eq!(s["state"], json!("running"));
|
||||
assert_eq!(s["discord"], json!("Jarvis#0001"));
|
||||
assert_eq!(s["voiceChannel"], json!("77"));
|
||||
assert_eq!(s["captions"][0]["text"], json!("자비스 안녕"));
|
||||
assert_eq!(s["voiceMembers"][0]["name"], json!("민수"));
|
||||
assert_eq!(s["worker"]["connected"], json!(true));
|
||||
assert!(s["system"]["ramTotalMb"].is_u64() || !cfg!(any(target_os = "linux", windows)));
|
||||
assert_eq!(s["performance"], Value::Null);
|
||||
c.stop().await.unwrap();
|
||||
let s = c.snapshot().await;
|
||||
assert_eq!(s["captions"], json!([]));
|
||||
assert_eq!(s["worker"], Value::Null);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user