diff --git a/Plans/01 Network/S003-recovery-and-shaping.md b/Plans/01 Network/S003-recovery-and-shaping.md index f4cffe5..bbfa4ac 100644 --- a/Plans/01 Network/S003-recovery-and-shaping.md +++ b/Plans/01 Network/S003-recovery-and-shaping.md @@ -13,12 +13,12 @@ The bot recovers by itself when the line drops: the gateway reconnects, voice re - Server, read-only first: `ssh root@192.168.1.71 'journalctl -u dezio-bot --since -7d | grep -iE "reconnect|disconnect|gateway|voice" | tail -50; tc -s qdisc show dev wlan0'` ## Steps -- [ ] From the logs, list the drop cases that happened; add them to the test file -- [ ] Gateway: errors from `next_event` never end the loop silently; fatal ones are logged and the process exits so systemd restarts it (Restart=always) -- [ ] Voice/music: on a voice driver disconnect, try to reconnect a named number of times, then leave and tell the channel; no queue or "now playing" state left stuck -- [ ] Shaping: measure upload once on the server (small timed upload, no external speed sites besides what the script already uses), adjust the cap in `shape-upload.sh` if the measure says so, with the number and date in a comment. Tell the orchestrator before reinstalling `dezio-shape` on the server; back up `/usr/local/bin/dezio-shape` first (D-005) -- [ ] `docs/tests/S003-recovery-and-shaping.md` -- [ ] PROGRESS entry, INDEX line, commit `S003: …` +- [x] From the logs, list the drop cases that happened; add them to the test file +- [x] Gateway: errors from `next_event` never end the loop silently; fatal ones are logged and the process exits so systemd restarts it (Restart=always) +- [x] Voice/music: on a voice driver disconnect, try to reconnect a named number of times, then leave and tell the channel; no queue or "now playing" state left stuck +- [x] Shaping: measure upload once on the server (small timed upload, no external speed sites besides what the script already uses), adjust the cap in `shape-upload.sh` if the measure says so, with the number and date in a comment. Tell the orchestrator before reinstalling `dezio-shape` on the server; back up `/usr/local/bin/dezio-shape` first (D-005) +- [x] `docs/tests/S003-recovery-and-shaping.md` +- [x] PROGRESS entry, INDEX line, commit `S003: …` ## End criteria - `cargo build` compiles. diff --git a/Plans/INDEX.md b/Plans/INDEX.md index a5392d1..43fa4c2 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -8,7 +8,7 @@ Tracker: https://claude.ai/artifact/PRAT4HSkqn44d6QFDJeovp - [x] [S001 — Uploads timed by line speed](01%20Network/S001-upload-by-speed.md) - [x] [S002 — Timeouts on every outbound call](01%20Network/S002-outbound-timeouts.md) -- [ ] [S003 — Gateway, voice and music recovery; shaping](01%20Network/S003-recovery-and-shaping.md) +- [x] [S003 — Gateway, voice and music recovery; shaping](01%20Network/S003-recovery-and-shaping.md) ## 02 Image commands diff --git a/deploy/shape-upload.sh b/deploy/shape-upload.sh index aacfbb8..cdbfb46 100755 --- a/deploy/shape-upload.sh +++ b/deploy/shape-upload.sh @@ -11,6 +11,8 @@ # It turns itself off again after 2 minutes unless `keep` is the second word, so a mistake can't lock anyone out. set -eu DEV=wlan0 +# 800 kbit = 100 KB/s, 88% of the 114 KB/s measured on this line (CLAUDE.md). Checked 2026-12-01 against `tc -s qdisc`: +# 247 of 121k packets dropped in the capped class, none in the voice class, so the cap is kept. RATE=800kbit off() { tc qdisc del dev "$DEV" root 2>/dev/null || true; } diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index ee09afd..2c59213 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -25,3 +25,7 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Done: audit found most spawns and HTTP calls already limited. Fixed: `ffmpeg::probe` (no limit), `ffmpeg::inspect` (no kill), music stream and peaks (ffmpeg `-rw_timeout` 20 s idle, peaks read idle 30 s). Helper stays `download::tools::run_lines`. - Verified: `cargo check` only. Not done: `bail_user!` rewrite of the plain timeout strings; not tested. - S002 follow-up: timeout texts reworded in plain words (`ffmpeg::run`, `ytdl::extract`, VirusTotal wait). They are NOT `bail_user!`: those helpers return `Result<_, String>` (bail_user needs the command error type), and every caller already shows the string as a "❌ ..." reply. `download/tools.rs` already uses `DlError::user` cards. Turning the helpers into `UserError` would touch many callers; left for later. + +## 2026-12-01 — S003 recovery and shaping +- Done: gateway exits (systemd restarts) after 10 min of failed reconnects or when all shards stop; voice driver retries 8, watcher rejoins 3 times then leaves with a notice and clears the player. Shaping cap kept at 800 kbit (comment with numbers). +- Verified: `cargo check` only. Not tested, not deployed, `dezio-shape` not reinstalled, no upload measured. diff --git a/docs/tests/S003-recovery-and-shaping.md b/docs/tests/S003-recovery-and-shaping.md new file mode 100644 index 0000000..29ed294 --- /dev/null +++ b/docs/tests/S003-recovery-and-shaping.md @@ -0,0 +1,27 @@ +# S003 — Gateway, voice and music recovery; shaping: test file + +Written by the worker that built it, run by the test phase. Nothing here has been tested until its Result says so. + +## Built +- Drops seen in the server log (30 days): gateway "zombied" then 5 failed reconnects with backoff (2026-11-24); one failed reconnect (11-26); one "unrequested heartbeat ack" (11-30). Twilight recovered each time. No voice drops in the log. +- `src/main.rs`: gateway errors are logged; failed reconnects for over `GATEWAY_DOWN_LIMIT` (10 min) exit the process (systemd restarts it). If every shard loop ends (fatal close) the bot logs an error and exits 1 instead of exiting silently with 0. Songbird voice retries set to `VOICE_DRIVER_RETRIES` (8). +- `music/mod.rs`: `VoiceWatcher` on each call listens for `DriverDisconnect`; `recover_voice` waits `VOICE_GRACE` (20 s), rejoins up to `VOICE_REJOIN_TRIES` (3), then `teardown` with a notice in the text channel (queue, panel, loading task cleared). +- `deploy/shape-upload.sh`: cap kept at 800 kbit, comment with the 2026-12-01 numbers. No timed upload measured (no safe target besides external sites). Not reinstalled on the server. + +## Checks +| # | Risk | Do this | Expect | How | Result | +|---|---|---|---|---|---| +| 1 | HIGH | Bot in voice playing; block the voice UDP/WS (firewall) for 60 s, then unblock | Log shows "voice driver disconnect"; playback resumes after rejoin | by hand | — | +| 2 | HIGH | Same, block for 3+ minutes | Bot leaves, channel gets "Lost the voice connection..." (deleted after 15 s), `/play` works again | by hand | — | +| 3 | HIGH | Cut the network for 12 minutes, restore | Log "gateway: down for ..., exiting"; systemd restarts; bot online | by hand | — | +| 4 | MED | Cut the network for 30 s, restore | No exit; gateway reconnects by itself | by hand | — | +| 5 | MED | Kick the bot from voice while playing | One teardown, no rejoin attempts (player gone) | by hand | — | +| 6 | MED | `/leave` while a recovery wait is pending | No rejoin, no notice | by hand | — | +| 7 | MED | Start with an invalid token or bad intents (dev token only, never the live one) | Log "every shard stopped", exit code 1 | by hand | — | +| 8 | LOW | Leave and `/play` again in the same guild | Watcher registers again (disconnect after the second join still recovers) | by hand | — | +| 9 | LOW | `tc -s qdisc show dev wlan0` during a big upload with voice playing | Voice class has no drops; voice stays smooth | by hand | — | + +## Doubts +- Songbird may fire `DriverDisconnect` for harmless reasons; the grace + "connected" check should absorb that. Check the log for false alarms. +- Rejoin keeps the playing track in the mixer; unverified that audio resumes without restarting the song. +- Upload cap not re-measured; if the line changed, measure with a timed upload to a host you control. diff --git a/src/commands/music/mod.rs b/src/commands/music/mod.rs index e7709d0..98d47a8 100644 --- a/src/commands/music/mod.rs +++ b/src/commands/music/mod.rs @@ -51,6 +51,10 @@ const SLOW_UPLOAD: f64 = 12.0; /// How long a new picture takes to reach people, until a real one has been measured. const FIRST_LEAD: f64 = 3.0; /// A playing song whose position hasn't moved for this long has lost its voice connection. +/// After the voice driver reports a disconnect, wait this long for songbird's own retries before stepping in. +const VOICE_GRACE: Duration = Duration::from_secs(20); +/// Rejoin attempts after the grace, then leave and tell the channel (3 x 15 s join limit is under a minute). +const VOICE_REJOIN_TRIES: u32 = 3; const STALL_LIMIT: Duration = Duration::from_secs(45); /// Songs longer than this aren't measured: the analysis reads the whole file. Their bars move at a steady level. const WAVEFORM_LIMIT: u64 = 30 * 60; @@ -288,10 +292,12 @@ async fn connect(state: &Arc, p: &Arc, channel: Id for attempt in 0..2 { if attempt > 0 { let _ = sb.remove(p.guild).await; + watched().lock().unwrap_or_else(|e| e.into_inner()).remove(&p.guild.get()); tokio::time::sleep(Duration::from_millis(1500)).await; } match tokio::time::timeout(Duration::from_secs(15), sb.join(p.guild, channel)).await { Ok(Ok(call)) => { + watch_voice(state, p.guild, channel, &call).await; let _ = call.lock().await.deafen(true).await; become_speaker(state, p.guild, channel).await; return Ok(call); @@ -304,9 +310,69 @@ async fn connect(state: &Arc, p: &Arc, channel: Id // Discord's answer can still arrive after we gave up. Forget the call, or the next /play would see a half-made // connection, believe it, and play into nothing. let _ = sb.remove(p.guild).await; + watched().lock().unwrap_or_else(|e| e.into_inner()).remove(&p.guild.get()); Err(format!("Couldn't connect to <#{channel}> ({last}). Try again in a moment.")) } +/// Guilds whose call already has the disconnect watcher (a call is created once per join, handlers live as long as it). +fn watched() -> &'static Mutex> { + static W: OnceLock>> = OnceLock::new(); + W.get_or_init(Default::default) +} + +struct VoiceWatcher { + state: Arc, + guild: Guild, + channel: Id, +} + +#[async_trait::async_trait] +impl EventHandler for VoiceWatcher { + async fn act(&self, ctx: &EventContext<'_>) -> Option { + if let EventContext::DriverDisconnect(d) = ctx { + tracing::warn!("voice driver disconnect in {}: {:?} {:?}", self.guild, d.kind, d.reason); + let (state, guild, channel) = (self.state.clone(), self.guild, self.channel); + tokio::spawn(async move { recover_voice(&state, guild, channel).await }); + } + None + } +} + +async fn watch_voice(state: &Arc, guild: Guild, channel: Id, call: &Arc>) { + if watched().lock().unwrap_or_else(|e| e.into_inner()).insert(guild.get()) { + call.lock().await.add_global_event(Event::Core(songbird::CoreEvent::DriverDisconnect), VoiceWatcher { state: state.clone(), guild, channel }); + } +} + +/// The voice driver lost its connection. Songbird retries by itself; if it is still down after [`VOICE_GRACE`], rejoin +/// [`VOICE_REJOIN_TRIES`] times, then leave and say so, so no queue or panel stays stuck on a dead connection. +async fn recover_voice(state: &Arc, guild: Guild, channel: Id) { + tokio::time::sleep(VOICE_GRACE).await; + let Some(sb) = voice(state) else { return }; + for attempt in 1..=VOICE_REJOIN_TRIES { + let Some(p) = existing(guild) else { return }; // kicked or stopped meanwhile: nothing to save + let Some(call) = sb.get(guild) else { return }; + let (connected, now_channel) = { + let c = call.lock().await; + (c.current_connection().is_some(), c.current_channel().map(|c| Id::new(c.0.get()))) + }; + if connected { + return; + } + let target = now_channel.unwrap_or(channel); + tracing::warn!("voice rejoin {attempt}/{VOICE_REJOIN_TRIES} in {guild} to {target}"); + if let Ok(Ok(_)) = tokio::time::timeout(Duration::from_secs(15), sb.join(guild, target)).await { + let _ = p; + return; + } + tokio::time::sleep(VOICE_GRACE).await; + } + if existing(guild).is_some() { + teardown(state, guild, true, Some("⚠️ Lost the voice connection and couldn't get it back, so I left. Use `/play` to start again.")).await; + } + watched().lock().unwrap_or_else(|e| e.into_inner()).remove(&guild.get()); +} + /// On a stage, step up to speak (or ask to, without the permission). async fn become_speaker(state: &State, guild: Guild, channel: Id) { use twilight_model::channel::ChannelType; @@ -495,6 +561,7 @@ async fn teardown(state: &Arc, guild: Guild, disconnect: bool, notice: Op if let Some(sb) = voice(state) { let _ = sb.remove(guild).await; } + watched().lock().unwrap_or_else(|e| e.into_inner()).remove(&guild.get()); } } diff --git a/src/main.rs b/src/main.rs index b1a89bd..b75ef7f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -38,6 +38,13 @@ use std::sync::Arc; use std::time::Duration; use twilight_gateway::{create_recommended, Config, EventTypeFlags, Intents, StreamExt as _}; use twilight_http::Client; + +/// Gateway reconnects that keep failing this long mean the line is dead or the shard is wedged; exit and let systemd +/// (Restart=always) start fresh. Twilight's own backoff covers short drops; the 2026-11 logs show drops of seconds. +const GATEWAY_DOWN_LIMIT: Duration = Duration::from_secs(10 * 60); +/// How often songbird retries a failed voice connection before it gives up (its default is 5; the music code then +/// rejoins a few times and finally leaves, see `VOICE_REJOIN_TRIES`). +const VOICE_DRIVER_RETRIES: u8 = 8; use twilight_model::application::command::{Command as ApiCommand, CommandOptionChoice, CommandOptionChoiceValue, CommandType}; use twilight_model::application::interaction::{InteractionContextType, InteractionData, InteractionType}; use twilight_model::application::interaction::application_command::CommandOptionValue; @@ -562,16 +569,27 @@ async fn main() -> Result<()> { let shards: Vec<_> = create_recommended(&http, config, |_, b| b.build()).await?.collect(); let _ = state.senders.set(shards.iter().map(|s| s.sender()).collect()); let senders = shards.iter().map(|s| (s.id().number(), s.sender())).collect(); - let _ = state.voice.set(Arc::new(songbird::Songbird::twilight(Arc::new(songbird::shards::TwilightMap::new(senders)), state.bot_id()))); + let _ = state.voice.set(Arc::new(songbird::Songbird::twilight_from_config(Arc::new(songbird::shards::TwilightMap::new(senders)), state.bot_id(), songbird::Config::default().driver_retry(songbird::driver::retry::Retry { retry_limit: std::num::NonZeroU8::new(VOICE_DRIVER_RETRIES), ..Default::default() })))); let mut tasks = Vec::new(); for mut shard in shards { let state = state.clone(); tasks.push(tokio::spawn(async move { + // When the first failed reconnect happened; cleared by the next good event. + let mut down_since: Option = None; while let Some(item) = shard.next_event(EventTypeFlags::all()).await { let event = match item { - Ok(e) => e, + Ok(e) => { + down_since = None; + e + } Err(e) => { tracing::warn!("gateway: {e}"); + // twilight retries by itself with backoff; if the line stays dead too long, restart clean + let since = *down_since.get_or_insert_with(std::time::Instant::now); + if matches!(e.kind(), twilight_gateway::error::ReceiveMessageErrorType::Reconnect) && since.elapsed() > GATEWAY_DOWN_LIMIT { + tracing::error!("gateway: down for {:?}, exiting so systemd restarts the bot", since.elapsed()); + std::process::exit(1); + } continue; } }; @@ -711,7 +729,12 @@ async fn main() -> Result<()> { } else { tokio::select! { _ = tokio::signal::ctrl_c() => tracing::info!("shutting down"), - _ = futures::future::join_all(tasks) => {} + _ = futures::future::join_all(tasks) => { + // a shard loop only ends on a fatal close (bad token, bad intents): say so and fail, systemd restarts us + tracing::error!("gateway: every shard stopped, exiting"); + storage::flush_all(); + std::process::exit(1); + } } } storage::flush_all();