diff --git a/Plans/INDEX.md b/Plans/INDEX.md index fd11177..df03f3f 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -6,7 +6,7 @@ Tracker: https://claude.ai/artifact/PRAT4HSkqn44d6QFDJeovp ## 01 Network -- [ ] [S001 — Uploads timed by line speed](01%20Network/S001-upload-by-speed.md) +- [x] [S001 — Uploads timed by line speed](01%20Network/S001-upload-by-speed.md) - [ ] [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) diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 992092b..994d475 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -14,5 +14,9 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Verified: `cargo test` (same 8 worktree-only asset failures); `cargo test covers_live -- --ignored` and `listenbrainz_live` pass. - Not done: not deployed at commit time; not checked in Discord 🧑. +## 2026-12-01 — S001 uploads by speed +- Done: `media::budget_for` / `upload_budget(ctx)` with `UPLOAD_SECONDS`=75 and `UPLOAD_BYTES_PER_SEC`=114_000 (reuse in S002, S008). Real limit 10 MiB. `/download` plans by budget, retries only reset/429/5xx, timeout becomes a website link. Convert and /media use the budget. +- Verified: `cargo check` only. Not done: pre-upload link for /download when too big; other attachment paths; per-call HTTP timeout. + ## Later -- (none yet) +- Per-request shorter timeout for plain Discord API calls: not done in S001. diff --git a/docs/tests/S001-upload-by-speed.md b/docs/tests/S001-upload-by-speed.md new file mode 100644 index 0000000..68f9487 --- /dev/null +++ b/docs/tests/S001-upload-by-speed.md @@ -0,0 +1,31 @@ +# S001 — Uploads timed by line speed: 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 +`src/commands/media/mod.rs` · `UPLOAD_SECONDS` (75), `UPLOAD_BYTES_PER_SEC` (114_000), `budget_for(limit)` pure, `upload_budget(ctx)`; `upload_limit` now 10/50/100 MiB. +`src/commands/media/download/mod.rs` · `/download` limit = budget; `upload()` retries only RequestError, 429, 5xx; timeout gives `DlError::UploadTimedOut`; `publish_link` hosts the files and shows links. +`convert.rs`, `images.rs` · use `upload_budget` (convert already hosts oversize via ffmpeg::convert_to). + +## Checks +| # | Risk | Do this | Expect | How | Result | +|---|---|---|---|---|---| +| 1 | MED | `cargo test budget_is_the_smaller` | passes | unit | — | +| 2 | MED | Tier 0/1 guild: read `upload_limit` | 10 MiB; tier 2 50, tier 3 100 | unit/by hand | — | +| 3 | HIGH | `/download` of a clip that compresses to ~8 MB | uploads as attachment, no retry loop | by hand | — | +| 4 | HIGH | `/download` source whose smallest encode is above 8.5 MB | "Too large" card (no link yet, see Doubts) | by hand | — | +| 5 | HIGH | Force upload timeout (shape line to a few KB/s or shorten client timeout locally) | one attempt only, message becomes hosted link(s) | by hand | — | +| 6 | MED | Simulate 502 or connection reset on upload | retried up to 3 times | by hand | — | +| 7 | MED | Simulate 400/403 on upload | no retry, "Discord refused" card | by hand | — | +| 8 | MED | `/convert` to a result over 8.5 MB | link with 24 h notice, no attachment | by hand | — | +| 9 | LOW | `/media` effect with result over budget | "too big to upload" error with MB values | by hand | — | +| 10 | LOW | `rg UPLOAD_RETRIES src` | retry loop only continues on retryable errors | by hand | — | + +## Needs +Discord test server and the Chromebook line; never the real token on this PC. + +## Doubts +- Timeout detection assumes twilight reports `RequestTimedOut` for the 180 s client timeout. +- `/download` still shows "Too large" when it cannot encode under the budget; no pre-upload link fallback added. +- Other attachment paths (music card, quote, games, cmd.rs) not changed: they are small images; per-request shorter timeout for API calls not done (see PROGRESS Later). +- `FALLBACK_UPLOAD_LIMIT` is now unused in download/mod.rs; may warn. diff --git a/src/commands/media/convert.rs b/src/commands/media/convert.rs index 97b0487..46c1f5c 100644 --- a/src/commands/media/convert.rs +++ b/src/commands/media/convert.rs @@ -11,7 +11,7 @@ //! Text version: `D!convert mp3 128k` (reply to a file, attach one, or add a link / @user). use super::ffmpeg::{self, find_format, parse_quality, Converted, MediaType, Quality, Source, HEIGHTS, KBPS}; use super::images::pick_opt; -use super::{fetch_limited, has_ext, safe_url, upload_limit, AUDIO_EXTS, IMAGE_EXTS, VIDEO_EXTS}; +use super::{fetch_limited, has_ext, safe_url, upload_budget, AUDIO_EXTS, IMAGE_EXTS, VIDEO_EXTS}; use crate::bail_user; use crate::cmd::{Command, Ctx, Opt, OptKind}; use crate::state::State; @@ -237,7 +237,7 @@ async fn convert_cmd(ctx: Arc) -> Result<()> { None => bail_user!("Attach a file, give a link, or post a picture, video or sound in this channel first — I convert the latest one."), }, }; - let limit = upload_limit(&ctx); + let limit = upload_budget(&ctx); ctx.defer().await?; let source = open_source(&ctx.state, &url).await?; let Some((kind, animated)) = ffmpeg::detect(&source).await else { bail_user!("I can't read that file as a picture, video or sound.") }; diff --git a/src/commands/media/download/job.rs b/src/commands/media/download/job.rs index 61d91a2..9b4e16a 100644 --- a/src/commands/media/download/job.rs +++ b/src/commands/media/download/job.rs @@ -15,6 +15,8 @@ pub enum DlError { /// The stream we started is bigger than the limit; try a smaller one. SizeExceeded, Cancelled, + /// The upload ran out of time; repeating it would time out again → send a link instead. + UploadTimedOut, /// Raw text from yt-dlp, for [`super::plan::friendly_error`]. Ytdlp(String), } diff --git a/src/commands/media/download/mod.rs b/src/commands/media/download/mod.rs index 159c3e3..2e51873 100644 --- a/src/commands/media/download/mod.rs +++ b/src/commands/media/download/mod.rs @@ -36,6 +36,7 @@ use twilight_util::builder::embed::{EmbedBuilder, ImageSource}; const UI_TICK: Duration = Duration::from_secs(5); const PROGRESS_PICTURE: &str = "download.jpg"; +/// Retries only for errors that can work the second time (connection reset, 5xx, rate limit). A timeout is never retried. const UPLOAD_RETRIES: u32 = 3; const BLURPLE: u32 = 0x5865F2; @@ -314,7 +315,11 @@ where if http_status(&e) == Some(413) || api_code(&e) == Some(40005) { return Err(DlError::TooLarge); } - if matches!(http_status(&e), Some(400 | 401 | 403 | 404)) { + if matches!(e.kind(), twilight_http::error::ErrorType::RequestTimedOut) { + return Err(DlError::UploadTimedOut); + } + let retryable = matches!(e.kind(), twilight_http::error::ErrorType::RequestError) || matches!(http_status(&e), Some(429 | 500..=599)); + if !retryable { return Err(DlError::user("Upload failed", format!("Discord refused the upload: {}", e.to_string().chars().take(200).collect::()))); } last = e.to_string(); @@ -348,7 +353,25 @@ async fn publish(job: &Job, live: &Live, paths: &[PathBuf], content: Option publish_link(job, live, paths, &content).await, + other => other, + } +} + +/// The upload timed out: keep the files on the website and show links instead. +async fn publish_link(_job: &Job, live: &Live, paths: &[PathBuf], content: &Option) -> Result<(), DlError> { + let mut text = content.clone().unwrap_or_default(); + text.push_str(&format!("\n📦 Discord upload was too slow from here, so it's kept for **{} hours**:", crate::hosted::TTL.as_secs() / 3600)); + for p in paths { + let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("file"); + match crate::hosted::store(p, name) { + Ok(link) => text.push_str(&format!("\n{link}")), + Err(e) => return Err(DlError::user("Upload failed", format!("The upload timed out and I couldn't keep the file for download ({e})."))), + } + } + let text: String = text.chars().take(1900).collect(); + live.edit(Some(&text), &[], &[], &[]).await.map_err(|e| DlError::user("Upload failed", format!("The upload timed out and the link couldn't be shown: {}", e.to_string().chars().take(100).collect::()))) } // ---- running a job ------------------------------------------------------------------------------------------ @@ -367,7 +390,7 @@ async fn download(ctx: Arc) -> Result<()> { if active().lock().unwrap_or_else(|e| e.into_inner()).contains_key(&owner) { return fail(&ctx, "Already busy", "You already have a download running.").await; } - let limit = super::upload_limit(&ctx).max(FALLBACK_UPLOAD_LIMIT as usize) as u64; + let limit = super::upload_budget(&ctx) as u64; let cap = if quality == "best" { DEFAULT_QUALITY_CAP } else { quality.parse().unwrap_or(DEFAULT_QUALITY_CAP) }; let job = Arc::new(Job::new(owner, url.clone(), limit, audio)); let live = Arc::new(Live::create(&ctx, &progress_embed(&job), &cancel_row(owner, false)).await?); diff --git a/src/commands/media/download/plan.rs b/src/commands/media/download/plan.rs index 6a683a4..f22cc2d 100644 --- a/src/commands/media/download/plan.rs +++ b/src/commands/media/download/plan.rs @@ -11,7 +11,7 @@ pub const MAX_DURATION_SECONDS: f64 = 30.0 * 60.0; pub const DEFAULT_QUALITY_CAP: i64 = 1080; pub const AUDIO_EXT: &str = "opus"; pub const AUDIO_KBPS: i64 = 96; -pub const FALLBACK_UPLOAD_LIMIT: u64 = 20 * 1024 * 1024; +pub const FALLBACK_UPLOAD_LIMIT: u64 = 10 * 1024 * 1024; pub const SAFETY_MARGIN: f64 = 0.95; pub const FINAL_MARGIN: f64 = 0.99; pub const BPP_MIN: f64 = 0.065; diff --git a/src/commands/media/images.rs b/src/commands/media/images.rs index dd04eb1..cddce6a 100644 --- a/src/commands/media/images.rs +++ b/src/commands/media/images.rs @@ -4,7 +4,7 @@ //! The picture can come from an attachment, the message you reply to, someone's avatar (@mention / //! name), a custom emoji or a link; with nothing given, your own avatar is used. GIFs keep their //! animation. Everything is drawn in a worker thread at a sensible size, so a big GIF can't freeze the bot. -use super::{avatar, custom_emojis, emoji_url, fetch_limited, has_ext, replied, safe_url, upload_limit, AUDIO_EXTS, IMAGE_EXTS, VIDEO_EXTS}; +use super::{avatar, custom_emojis, emoji_url, fetch_limited, has_ext, replied, safe_url, upload_budget, AUDIO_EXTS, IMAGE_EXTS, VIDEO_EXTS}; use crate::bail_user; use crate::cmd::{Command, Ctx, Opt, OptKind}; use crate::converters::find_member; @@ -405,7 +405,7 @@ fn resolve_name(name: &str) -> (Option<&'static str>, Option<&'static str>) { /// Effects and filters on a picture or GIF: the shared job behind `/media` and `D!fx`. async fn run_job(ctx: &Arc, url: &str, effect: Option<&'static str>, filter: Option<&'static str>, opts: Opts) -> Result<()> { - let limit = upload_limit(ctx); + let limit = upload_budget(ctx); ctx.defer().await?; let Some(data) = fetch_limited(&ctx.state, url, MAX_IMAGE_BYTES).await else { bail_user!("I couldn't download that ({} MB max).", MAX_IMAGE_BYTES / 1024 / 1024); diff --git a/src/commands/media/mod.rs b/src/commands/media/mod.rs index 5ecef79..1a56481 100644 --- a/src/commands/media/mod.rs +++ b/src/commands/media/mod.rs @@ -126,17 +126,32 @@ pub fn emoji_url(id: u64, animated: bool, size: u32) -> String { format!("https://cdn.discordapp.com/emojis/{id}.{}?size={size}", if animated { "gif" } else { "png" }) } -/// Upload limit for files in this server: Discord's default is 20 MiB since September 2026, more with boosts. +/// Upload limit for files in this server: Discord's real bot limit, 10 MiB by default, more with boosts. pub fn upload_limit(ctx: &Ctx) -> usize { let tier = ctx.guild_id.and_then(|g| ctx.state.cache.guild(g).map(|g| u8::from(g.premium_tier()))).unwrap_or(0); let mb: usize = match tier { 2 => 50, 3 => 100, - _ => 20, + _ => 10, }; mb * 1024 * 1024 } +/// How long one upload may take. Under the 180 s Discord client timeout, with room for voice traffic. +pub const UPLOAD_SECONDS: usize = 75; +/// Upload speed of the server's line: measured 114 KB/s on 2026-11-12 (CLAUDE.md section 2). +pub const UPLOAD_BYTES_PER_SEC: usize = 114_000; + +/// Pure budget math: the smaller of Discord's limit and what the line can send in [`UPLOAD_SECONDS`]. +pub fn budget_for(discord_limit: usize) -> usize { + discord_limit.min(UPLOAD_SECONDS * UPLOAD_BYTES_PER_SEC) +} + +/// Bytes one upload may have in this server. Bigger results go to the website as a link. +pub fn upload_budget(ctx: &Ctx) -> usize { + budget_for(upload_limit(ctx)) +} + #[allow(dead_code)] pub fn need(value: Option, text: &str) -> Result { match value { @@ -149,6 +164,13 @@ pub fn need(value: Option, text: &str) -> Result { mod tests { use super::*; + #[test] + fn budget_is_the_smaller_of_limit_and_line() { + assert_eq!(budget_for(10 * 1024 * 1024), UPLOAD_SECONDS * UPLOAD_BYTES_PER_SEC); + assert_eq!(budget_for(1000), 1000); + assert!(budget_for(100 * 1024 * 1024) <= 10 * 1024 * 1024); + } + #[test] fn private_addresses_are_refused() { assert!(safe_url("https://example.com/a.png").is_some());