From a1a3a96c722e9e10bf6017a3aaa1d93a4e65c575 Mon Sep 17 00:00:00 2001 From: unRekable Date: Fri, 4 Dec 2026 14:35:28 +0100 Subject: [PATCH] Stopping a Telegram download ends it at the piece on its way and leaves no part file behind --- crates/chatd/src/adapters/mod.rs | 5 + crates/chatd/src/adapters/telegram.rs | 7 + crates/chatd/src/adapters/telegram/fake.rs | 14 +- crates/chatd/src/adapters/telegram/files.rs | 116 +++++++- crates/chatd/src/demo/adapter.rs | 1 + crates/chatd/src/server.rs | 9 + crates/chatd/tests/telegram.rs | 68 +++++ crates/protocol/src/lib.rs | 9 + crates/tinyclient/src/client.rs | 2 + docs/architecture.md | 1 + .../telegram-cancel-download/drive.linux.sh | 9 + .../telegram-cancel-download/drive.macos.sh | 9 + .../telegram-cancel-download/drive.py | 281 ++++++++++++++++++ .../drive.windows.ps1 | 17 ++ .../telegram-cancel-download/scenario.json | 12 + 15 files changed, 548 insertions(+), 12 deletions(-) create mode 100644 e2e/scenarios/telegram-cancel-download/drive.linux.sh create mode 100644 e2e/scenarios/telegram-cancel-download/drive.macos.sh create mode 100644 e2e/scenarios/telegram-cancel-download/drive.py create mode 100644 e2e/scenarios/telegram-cancel-download/drive.windows.ps1 create mode 100644 e2e/scenarios/telegram-cancel-download/scenario.json diff --git a/crates/chatd/src/adapters/mod.rs b/crates/chatd/src/adapters/mod.rs index 0d1a01bc..7481229c 100644 --- a/crates/chatd/src/adapters/mod.rs +++ b/crates/chatd/src/adapters/mod.rs @@ -1914,6 +1914,11 @@ pub enum Command { ids: Vec, span: (u64, u64), }, + /// The user stopped the download of this file (`Request::CancelDownload`). An adapter that + /// fetches files over its own session stops at the piece on its way and keeps nothing of + /// the file on disk; a file already on disk stays, and nothing is announced. The player's + /// byte windows are not downloads. Others ignore it. + CancelDownload { id: String }, /// The link that opens this conversation's call in the official app. Handoff { conversation_id: String, reply: Reply }, /// A stage hand, an accepted invite, or a moderator moving someone. diff --git a/crates/chatd/src/adapters/telegram.rs b/crates/chatd/src/adapters/telegram.rs index 49bac929..525ca980 100644 --- a/crates/chatd/src/adapters/telegram.rs +++ b/crates/chatd/src/adapters/telegram.rs @@ -804,6 +804,13 @@ pub fn start(ctx: Context, session: &str, inbox: Receiver) -> Result<() .spawn(move || deliver_cancel(&account, &conversation_id)); } } + // Off `telegram-commands`, like a send's cancel: a history fetch held there + // must not hold the stop too. + Command::CancelDownload { id } => { + if let Some(account) = account() { + account.files.cancel(&id); + } + } Command::Previews(ids) => { let _ = preview_tx.send(ids); } diff --git a/crates/chatd/src/adapters/telegram/fake.rs b/crates/chatd/src/adapters/telegram/fake.rs index 543e6545..f07e6905 100644 --- a/crates/chatd/src/adapters/telegram/fake.rs +++ b/crates/chatd/src/adapters/telegram/fake.rs @@ -2256,8 +2256,9 @@ pub struct Fake { /// `TINYCLIENT_TELEGRAM_PEER_HOLD`), until a line steers it through. hold_pages: bool, hold_peer_dialogs: bool, - /// And the row's size of `photo-preview`'s photo (`TINYCLIENT_TELEGRAM_FILE_HOLD`), until - /// `file-go`: what a slow download looks like while the stripped preview is on screen. + /// And some files (`TINYCLIENT_TELEGRAM_FILE_HOLD`, [`held_file`]) until `file-go`: the + /// row's size of `photo-preview`'s photo, which is what a slow download looks like while + /// the stripped preview is on screen, and the document `big-file` posts, which is one to stop. hold_files: bool, /// Wakes an answer held at the wire when the test steers. wake: Arc, @@ -2329,10 +2330,17 @@ impl Fake { // asked again until the `peer-go`. (self.hold_pages && asked::(body).is_some_and(|request| !matches!(request.offset_peer, tl::enums::InputPeer::Empty)) && !world.dialogs_go) || (self.hold_peer_dialogs && asked::(body).is_some() && !world.peer_go) - || (self.hold_files && asked::(body).is_some_and(|request| is_ridge_thumb(&request.location)) && !world.file_go) + || (self.hold_files && asked::(body).is_some_and(|request| held_file(&request.location)) && !world.file_go) } } +/// The files `TINYCLIENT_TELEGRAM_FILE_HOLD` holds at the wire until `file-go`: the row's size +/// of `photo-preview`'s photo, and the document `big-file` posts. +fn held_file(location: &tl::enums::InputFileLocation) -> bool { + is_ridge_thumb(location) + || matches!(location, tl::enums::InputFileLocation::InputDocumentFileLocation(document) if document.id == 9_400) +} + /// The row's size of `photo-preview`'s photo. fn is_ridge_thumb(location: &tl::enums::InputFileLocation) -> bool { matches!(location, tl::enums::InputFileLocation::InputPhotoFileLocation(photo) if photo.id == RIDGE && photo.thumb_size == "m") diff --git a/crates/chatd/src/adapters/telegram/files.rs b/crates/chatd/src/adapters/telegram/files.rs index 997be20b..c3723a7e 100644 --- a/crates/chatd/src/adapters/telegram/files.rs +++ b/crates/chatd/src/adapters/telegram/files.rs @@ -12,8 +12,10 @@ //! at its front. So a channel opened after another does not wait behind the first one's //! pictures, nor behind its own that are not on screen yet. A picture the shell asks for before //! a page has named it here goes ahead once a page does. A picker's tiles keep their turn: a -//! picker asks for a whole tab at once. The file being fetched is never cut short, and the -//! line never holds more than [`WAITING`]: past it, the last a page named is let go first. +//! picker asks for a whole tab at once. The file being fetched is never cut short for another, +//! and the line never holds more than [`WAITING`]: past it, the last a page named is let go +//! first. What the user stopped ([`Files::cancel`]) is the one exception: the piece of it on +//! its way is the last. //! // CONTRACT: an adapter has no way to hand the media cache a file. This does what the cache does // when one lands (`Store::register_media`, `Store::media_landed`, `Change::Media`) and nothing @@ -93,6 +95,8 @@ enum Job { Seen(Box, Instant), /// What is on screen changed: rows that came back put their pictures back in line. Look, + /// The user stopped the download of this file ([`Files::cancel`]). + Cancel(String), } pub struct Files { @@ -100,6 +104,9 @@ pub struct Files { jobs: Sender, waiting: Arc, held: Mutex, + /// The files whose download the user stopped, until the fetching thread looked at it: the + /// file being fetched ends at its next piece, and one waiting its turn is let go. + stops: Arc>>, } /// What the shell may ask for by id, and what it asked for before it was known here. @@ -312,6 +319,16 @@ impl Line { } gone } + + /// The user stopped the download: out of the line, wherever it waited its turn. The + /// player's byte windows are not downloads and stay. Answers how many places it had. + fn forget(&mut self, id: &str) -> usize { + let before = self.len(); + self.first.retain(|held| held.file.id != id); + self.seen.retain(|(_, held)| held.file.id != id); + self.rest.retain(|held| held.file.id != id); + before - self.len() + } } impl Files { @@ -319,8 +336,9 @@ impl Files { pub fn start(ctx: &Context) -> Files { let (jobs, inbox) = channel::(); let waiting = Arc::new(AtomicUsize::new(0)); + let stops = Arc::new(Mutex::new(HashSet::new())); let keeper = ctx.clone(); - let (ctx, counted) = (ctx.clone(), waiting.clone()); + let (ctx, counted, halts) = (ctx.clone(), waiting.clone(), stops.clone()); let spawned = std::thread::Builder::new().name("telegram-files".into()).spawn(move || { let mut account = Weak::new(); // Datacenters this connection's sign-in has been carried to. @@ -383,6 +401,16 @@ impl Files { } } Job::Look => rows_back(&account, &mut parked, &mut line.rest, &counted), + Job::Cancel(id) => { + // Nothing is fetched while a job is handled, so this stop was for + // what waits its turn: that lets go of its place, and the stop is + // spent. + let in_line = line.forget(&id); + let before = parked.len(); + parked.retain(|(_, held)| held.file.id != id); + counted.fetch_sub(in_line + before - parked.len(), Ordering::Relaxed); + crate::hub::lock(&halts).remove(&id); + } } // What the shell asks for is never refused at the door, so the line keeps // its own limit, parked pictures counted. @@ -425,7 +453,15 @@ impl Files { continue; } counted.fetch_sub(1, Ordering::Relaxed); - if let Err(fault) = fetch(&account, &want, &mut carried) { + let outcome = fetch(&account, &want, &mut carried); + // A stop that came as the last piece landed stopped nothing: it is not + // kept for the next ask. + crate::hub::lock(&halts).remove(&want.file.id); + if let Err(fault) = outcome { + // The user stopped it: nothing went wrong, and nothing is kept. + if fault == cancelled() { + continue; + } // A reference that ran out is renewed by the next page that names the file. if !fault.is("FILE_REFERENCE_EXPIRED") { tracing::warn!("chatd: Telegram: file {}: {fault}", want.file.id); @@ -445,7 +481,7 @@ impl Files { if let Err(err) = spawned { tracing::warn!("chatd: Telegram: files: {err}"); } - Files { ctx: keeper, jobs, waiting, held: Mutex::default() } + Files { ctx: keeper, jobs, waiting, held: Mutex::default(), stops } } pub fn attach(&self, account: &Arc) { @@ -478,7 +514,7 @@ impl Files { let (inline, wants): (Vec, Vec) = wants.into_iter().partition(|want| want.inline.is_some() && !want.original); for want in inline { let bytes = want.inline.as_deref().unwrap_or_default(); - if let Err(fault) = keep(&self.ctx, &want, |out, _| write_inline(out, bytes)) { + if let Err(fault) = keep(&self.ctx, &want, &|| false, |out, _| write_inline(out, bytes)) { tracing::warn!("chatd: Telegram: file {}: {fault}", want.file.id); } } @@ -513,6 +549,22 @@ impl Files { count } + /// The user stopped the download of this file. One waiting its turn lets go of its place at + /// once, and so does an ask no page has answered yet; the piece being fetched now is the + /// last, and nothing is kept of the file on disk. A file already on disk stays, and asking + /// for the file again fetches it from the start. + pub fn cancel(&self, id: &str) { + crate::hub::lock(&self.held).early.remove(id); + crate::hub::lock(&self.stops).insert(id.to_owned()); + let _ = self.jobs.send(Job::Cancel(id.to_owned())); + } + + /// Whether the user stopped the download of this file and the fetching thread did not look + /// at it yet. + fn stopped(&self, id: &str) -> bool { + crate::hub::lock(&self.stops).contains(id) + } + /// Sends what the shell asked for: never refused here, however many wait. The fetching /// thread keeps the line to [`WAITING`] by letting go of what matters least (`Line::trim`). fn ahead(&self, jobs: Vec) { @@ -856,7 +908,8 @@ fn fetch_span( /// One file, from Telegram to the cache's directory. fn fetch(account: &Account, want: &Want, carried: &mut HashSet) -> Result<(), Fault> { - let written = keep(&account.ctx, want, |out, start| match &want.inline { + let stopped = || account.files.stopped(&want.file.id); + let written = keep(&account.ctx, want, &stopped, |out, start| match &want.inline { Some(bytes) => write_inline(out, bytes), None => download(account, want, carried, start, out), })?; @@ -876,8 +929,9 @@ fn write_inline(out: &mut std::fs::File, bytes: &[u8]) -> Result { } /// One file into the cache's directory, written by `write`, and recorded as the cache records -/// a file that landed. `false` when it was on disk already and nothing was written. -fn keep(ctx: &Context, want: &Want, write: impl FnOnce(&mut std::fs::File, u64) -> Result) -> Result { +/// a file that landed. `false` when it was on disk already and nothing was written. While +/// `stopped` says so the user stopped the download: nothing is kept of it then. +fn keep(ctx: &Context, want: &Want, stopped: &dyn Fn() -> bool, write: impl FnOnce(&mut std::fs::File, u64) -> Result) -> Result { let id = std::slice::from_ref(&want.file.id); let on_disk = |ctx: &Context| { let known = ctx.hub.store().media(&ctx.account, id).unwrap_or_default(); @@ -915,6 +969,11 @@ fn keep(ctx: &Context, want: &Want, write: impl FnOnce(&mut std::fs::File, u64) }; let written = write(&mut out, start); drop(out); + // The user stopped the download, however its last piece ended: nothing is kept of it. + if want.inline.is_none() && stopped() { + let _ = std::fs::remove_file(&part); + return Err(cancelled()); + } let bytes = match written { Ok(bytes) => bytes, Err(fault) => { @@ -1006,6 +1065,11 @@ fn mismatched() -> Fault { Fault::Net("Telegram's copy of this file did not match.".to_owned()) } +/// The user stopped this download (`Command::CancelDownload`): nothing went wrong with it. +fn cancelled() -> Fault { + Fault::Net("stopped by the user".to_owned()) +} + type AesCtr = Ctr128BE; /// The counter Telegram's CDN uses: the redirect's IV plus `offset / 16`, big-endian. @@ -1070,6 +1134,10 @@ fn download(account: &Account, want: &Want, carried: &mut HashSet, start: u if account.ctx.pause(PACE) { return Err(Fault::Net("stopped".to_owned())); } + // The user stopped it meanwhile: no piece is asked for after that. + if account.files.stopped(&want.file.id) { + return Err(cancelled()); + } let request = tl::functions::upload::GetFile { precise: false, // A CDN redirect names a data centre the library cannot reach or key, so the file @@ -1084,6 +1152,10 @@ fn download(account: &Account, want: &Want, carried: &mut HashSet, start: u // A flood wait is honored in full here as everywhere. Err(fault) => match fault.flood() { Some(seconds) if seconds <= wire::PATIENCE && !pause(std::time::Duration::from_secs(seconds)) => { + // The wait may have been long, and the user may have stopped it meanwhile. + if account.files.stopped(&want.file.id) { + return Err(cancelled()); + } wire::call_in(wire, dc, &request)? } _ => return Err(fault), @@ -1163,6 +1235,10 @@ fn download_cdn( if account.ctx.pause(PACE) { return Err(Fault::Net("stopped".to_owned())); } + // The user stopped it meanwhile: no piece is asked for after that. + if account.files.stopped(&want.file.id) { + return Err(cancelled()); + } let request = tl::functions::upload::GetCdnFile { file_token: redirect.file_token.clone(), offset: offset as i64, @@ -1390,6 +1466,27 @@ mod tests { assert_eq!(order(line), ["original"]); } + #[test] + fn a_stopped_download_leaves_the_line_wherever_it_waits_but_not_the_players_windows() { + let mut line = Line::default(); + let at = Instant::now(); + assert!(!line.first(file("original", MediaKind::File, true, 1))); + assert!(!line.seen(thumb("a1"), at)); + assert!(!line.fetch(thumb("a2"))); + // The player's window of a file that also waits whole is not a download. + assert!(!line.span(file("video", MediaKind::Video, false, 1), (0, 1))); + assert!(!line.first(file("video", MediaKind::Video, true, 1))); + assert_eq!(line.forget("original"), 1, "the viewer's original"); + assert_eq!(line.forget("a1"), 1, "a picture on screen"); + assert_eq!(line.forget("a2"), 1, "a picture a page named"); + assert_eq!(line.forget("original"), 0, "it is gone already"); + assert_eq!(line.forget("nowhere"), 0, "nothing waits under that name"); + assert_eq!(line.forget("video"), 1, "the whole file goes, its window does not"); + assert_eq!(line.len(), 1); + assert!(line.pop_work().is_some_and(|work| matches!(work, NextWork::Span(_, (0, 1))))); + assert!(line.is_empty()); + } + #[test] fn what_is_remembered_keeps_the_latest_half_and_a_name_read_again_stays() { let mut recent = Recent::new(2); @@ -1422,6 +1519,7 @@ mod tests { Job::Seen(want, _) => ("seen", want.file.id), Job::Attach(_) => ("attach", String::new()), Job::Look => ("look", String::new()), + Job::Cancel(id) => ("cancel", id), }).collect() } diff --git a/crates/chatd/src/demo/adapter.rs b/crates/chatd/src/demo/adapter.rs index e9fd7828..4cf8f32e 100644 --- a/crates/chatd/src/demo/adapter.rs +++ b/crates/chatd/src/demo/adapter.rs @@ -1515,6 +1515,7 @@ impl Demo { | Command::Watch(_) | Command::Wanted(_) | Command::WantedSpan { .. } + | Command::CancelDownload { .. } | Command::TelegramCallSignal { .. } | Command::TelegramAcceptLoginToken { .. } | Command::TelegramCallSpeaking { .. } diff --git a/crates/chatd/src/server.rs b/crates/chatd/src/server.rs index ff692b2c..28e2c572 100644 --- a/crates/chatd/src/server.rs +++ b/crates/chatd/src/server.rs @@ -6674,6 +6674,15 @@ impl Chat { Err(err) => internal(err), } } + Request::CancelDownload { account, id } => { + // Only an adapter that fetches files over its own session (Telegram) has a + // download of its own to stop; the others let the command pass. + let adapter = lock(&self.adapters).get(&account).map(Adapter::sender); + if let Some(adapter) = adapter { + let _ = adapter.send(Command::CancelDownload { id }); + } + Response::Ok + } Request::FetchPreview { account, ids, max_bytes } => { let adapter = lock(&self.adapters).get(&account).map(Adapter::sender); let ids = &ids[..ids.len().min(PAGE_LIMIT as usize)]; diff --git a/crates/chatd/tests/telegram.rs b/crates/chatd/tests/telegram.rs index cd41dddc..f44f9cb3 100644 --- a/crates/chatd/tests/telegram.rs +++ b/crates/chatd/tests/telegram.rs @@ -3394,6 +3394,74 @@ fn a_dropped_large_file_resumes_from_the_part() { assert!(world.called("GetFile document 9400 at 1048576") >= 1, "{:#?}", world.calls()); } +/// Where the download of a Telegram file is kept while it is on its way. +fn part_path(world: &World, id: &str) -> PathBuf { + chatd::blobs::path_of(&world.dir.join("media"), &account(), id).with_extension("part") +} + +/// Asks chatd to stop a download, in the wire's own words: a chatd from before the request +/// answers `Unsupported`, and the download runs on. +fn stop_download(world: &World, id: &str) -> Response { + let mut stream = ChatStream::connect(&world.dir.join("chat.sock")).unwrap(); + write_frame(&mut stream, &serde_json::json!({"op": "cancel_download", "account": account(), "id": id})).unwrap(); + read_frame(&mut stream).unwrap() +} + +#[test] +fn a_stopped_download_ends_at_its_next_piece_and_leaves_no_part() { + let world = World::with(Some(SESSION), "30", &[("TINYCLIENT_TELEGRAM_FILE_HOLD", "1")]); + world.connected(); + world.watch(Watching { conversation: Some(key("u7002")), ..Watching::default() }); + world.until("history", || world.message("u7002", "12")); + world.steer("big-file"); + assert_eq!(world.arrived("u7002", "31").attachments[0].file.id, "d9400"); + // The user opened it: Telegram is asked for the first piece, which the wire holds. + assert_eq!(fetch_path(&world, "d9400"), None); + world.until("the first piece asked for", || (world.called("GetFile document 9400 at 0") > 0).then_some(())); + world.until("the part file", || part_path(&world, "d9400").exists().then_some(())); + assert_eq!(stop_download(&world, "d9400"), Response::Ok); + world.steer("file-go"); + // The piece on its way was the last: nothing more is asked for, and nothing is kept. + world.until("the part file gone", || (!part_path(&world, "d9400").exists()).then_some(())); + assert_eq!(world.called("GetFile document 9400 at 1048576"), 0, "{:#?}", world.calls()); + // Nothing landed. (The store lists a Telegram file only once it lands, so there is no row + // of it to ask for.) + assert!(!part_path(&world, "d9400").exists(), "the part file is gone"); + assert!(!chatd::blobs::path_of(&world.dir.join("media"), &account(), "d9400").exists(), "nothing landed"); + // Asked for again, it is fetched from the start and lands whole. + let landed = world.until("the file on disk", || fetch_path(&world, "d9400")); + let expected: Vec = (0..(1024 * 1024 + 64)).map(|at| (at % 251) as u8).collect(); + assert_eq!(std::fs::read(&landed).unwrap(), expected); + assert_eq!(world.called("GetFile document 9400 at 0"), 2, "{:#?}", world.calls()); +} + +#[test] +fn a_download_stopped_while_it_waits_its_turn_is_never_asked_for() { + let world = World::with(Some(SESSION), "30", &[("TINYCLIENT_TELEGRAM_FILE_HOLD", "1")]); + world.connected(); + world.watch(Watching { conversation: Some(key("u7002")), ..Watching::default() }); + world.until("history", || world.message("u7002", "12")); + // The big file is opened first, and the wire holds its first piece. + world.steer("big-file"); + world.arrived("u7002", "31"); + assert_eq!(fetch_path(&world, "d9400"), None); + world.until("the first piece asked for", || (world.called("GetFile document 9400 at 0") > 0).then_some(())); + // A photo comes while the chat is open, so its thumbnail waits behind the big file. The + // line after it is on screen: that proves the thumbnail was queued before the stop. + world.steer("photo"); + world.steer("incoming"); + world.arrived("u7002", "13"); + assert_eq!(stop_download(&world, "p6014m"), Response::Ok); + world.steer("file-go"); + world.until("the big file asked to its end", || (world.called("GetFile document 9400 at 1048576") > 0).then_some(())); + sleep(Duration::from_millis(1_500)); + assert_eq!(world.called("GetFile photo 6014 m"), 0, "{:#?}", world.calls()); + // Asked for again, it is fetched as any picture is. + let thumb = world.until("the thumbnail on disk", || fetch_path(&world, "p6014m")); + assert_eq!(std::fs::read(&thumb).unwrap(), (0..FILE_BYTES).map(|at| (at % 251) as u8).collect::>()); + assert_eq!(world.called("GetFile photo 6014 m at 0"), 1, "{:#?}", world.calls()); +} + #[test] fn a_link_preview_telegram_finishes_later_reaches_the_message() { let world = World::signed_in(); diff --git a/crates/protocol/src/lib.rs b/crates/protocol/src/lib.rs index 9db39429..2f2d3f13 100644 --- a/crates/protocol/src/lib.rs +++ b/crates/protocol/src/lib.rs @@ -3270,6 +3270,15 @@ pub enum Request { span: Option<(u64, u64)>, }, + /// Stops fetching this file. The piece on its way is the last, nothing is kept of it on + /// disk, and a file already on disk stays. Nothing is announced: asking for the file again + /// (`Fetch`) fetches it from the start. Answers `Ok` at once. Only a network that fetches + /// files over its own session (Telegram) has a download to stop; the others do nothing. + CancelDownload { + account: AccountKey, + id: String, + }, + /// Fetches at most `max_bytes` (clamped to [`TEXT_PREVIEW_MAX_BYTES`]) from the head of /// registered file attachments via a ranged HTTP request through chatd's media cache, for /// inline text/code previews. Returned [`MediaFile`] ids carry a `"head:"` prefix so full diff --git a/crates/tinyclient/src/client.rs b/crates/tinyclient/src/client.rs index c3283683..f64710a9 100644 --- a/crates/tinyclient/src/client.rs +++ b/crates/tinyclient/src/client.rs @@ -370,6 +370,8 @@ mod tests { "UserGroupUpdate", "UserGroupMembers", "SectionCreate", "SectionRename", "SectionDelete", "SectionReorder", // chatd sends this one to itself when a voice message starts playing. "MarkPlayed", + // The window's own way to stop a download is not built yet; the request is. + "CancelDownload", ]; fn sources(dir: &std::path::Path, into: &mut String) { diff --git a/docs/architecture.md b/docs/architecture.md index 846ea8fd..20fa95d0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -65,6 +65,7 @@ Seven adapters ship, one per `Network::ALL`, started from `adapters::start`: Dis | `Reactions {conversation}` | `Reactions {conversation, rules}` (kept 5 min) | `Command::ReactionRules` | | `Edit {.., text}`, `Delete {..}` | `Ok` once the network accepted | `Command::Edit` / `Delete`. Discord, Telegram and Tiny do this. An adapter that does not answers `Unsupported`. | | `Fetch {account, ids, size, retry}` | `Media {files}` | store (size, retry); `blobs` | +| `CancelDownload {account, id}` | `Ok` | `Command::CancelDownload`. Telegram stops the download at the piece on its way and keeps no part file of it; the others do nothing. | | `SignIn {network, at}`, `SignOut {account}` | `Status` | server | | `CallStart`, `CallAccept`, `CallDecline`, `CallEnd`, `CallSet`, `Media(..)` | `Status` | `media::Calls`; `Command::Call*` | | `Play(Start {account, file, path, conversation, message, title, at, rate, output} \| Pause \| Seek {at} \| Rate {rate} \| Stop)` | `Ok`; then `Change::Playback` | `playback::Player`; `mediad --play` | diff --git a/e2e/scenarios/telegram-cancel-download/drive.linux.sh b/e2e/scenarios/telegram-cancel-download/drive.linux.sh new file mode 100644 index 00000000..a6a1c335 --- /dev/null +++ b/e2e/scenarios/telegram-cancel-download/drive.linux.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# telegram-cancel-download on Linux. The lab runs this with bash while ffmpeg films the display. +set -u +HERE=$(cd "$(dirname "$0")" && pwd) +if command -v python3 >/dev/null 2>&1; then + exec python3 "$HERE/drive.py" +fi +echo "python3 is not on PATH" >&2 +exit 1 diff --git a/e2e/scenarios/telegram-cancel-download/drive.macos.sh b/e2e/scenarios/telegram-cancel-download/drive.macos.sh new file mode 100644 index 00000000..5309da5c --- /dev/null +++ b/e2e/scenarios/telegram-cancel-download/drive.macos.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# telegram-cancel-download on macOS. The lab runs this with bash while the display is filmed. +set -u +HERE=$(cd "$(dirname "$0")" && pwd) +if command -v python3 >/dev/null 2>&1; then + exec python3 "$HERE/drive.py" +fi +echo "python3 is not on PATH" >&2 +exit 1 diff --git a/e2e/scenarios/telegram-cancel-download/drive.py b/e2e/scenarios/telegram-cancel-download/drive.py new file mode 100644 index 00000000..3e30f7fc --- /dev/null +++ b/e2e/scenarios/telegram-cancel-download/drive.py @@ -0,0 +1,281 @@ +#!/usr/bin/env python3 +"""Stopping a Telegram download ends it at the piece on its way and leaves no part file behind. + +Starts this build's chatd with the scripted Telegram wire (TINYCLIENT_TELEGRAM_FAKE) on an +isolated profile, steers it over its control file the way tests/telegram.rs does, and speaks +chatd's real socket. A file the user opened is asked of Telegram piece by piece; the wire holds +the first piece; the shell stops the download; the wire lets go. Then Telegram is not asked for +the rest, the part file is gone and nothing landed. Asking for the file again fetches it from +the start and it lands whole. A build from before the fix does not know the request (it answers +an error), asks Telegram for the rest of the file and keeps the part file, so this driver fails +there. + +Env from the lab: E2E_OUT, E2E_T0, E2E_APP_DIR. +""" + +import json +import os +import socket +import struct +import subprocess +import sys +import time + +OUT = os.environ.get("E2E_OUT", "") +T0 = float(os.environ.get("E2E_T0") or time.time()) +APP = os.environ.get("E2E_APP_DIR", "") + +ME = "7001" +CHAT = "u7002" +SESSION = json.dumps({"user": 7001, "name": "Mira Kessler", "home": 2, "dcs": []}) +# What `big-file` posts into the chat: a document Telegram serves as one piece of a megabyte +# and 64 bytes more. +FILE = "d9400" +FILE_BYTES = 1024 * 1024 + 64 +# What another run of the fake, or a lab machine, may have left in the environment. +KNOBS = ("TINYCLIENT_TELEGRAM_HOLD", "TINYCLIENT_TELEGRAM_PEER_HOLD", "TINYCLIENT_TELEGRAM_MANY", "TINYCLIENT_TELEGRAM_PREMIUM") +ACCOUNT = {"network": "telegram", "account": ME} + +FAILED = False +STEPS = "" + + +def now(): + return time.time() - T0 + + +def step(words, ok): + global FAILED + if not ok: + FAILED = True + line = '{"t": %s, "step": "%s", "ok": %s}' % (round(now(), 1), words.replace('"', "'"), "true" if ok else "false") + print(("[ok] " if ok else "[FAILED] ") + words, flush=True) + if STEPS: + with open(STEPS, "a", encoding="utf-8") as handle: + handle.write(line + "\n") + + +def app_bin(app_dir): + name = "chatd.exe" if sys.platform == "win32" else "chatd" + if sys.platform == "darwin" and app_dir.endswith(".app"): + return os.path.join(app_dir, "Contents", "MacOS", "chatd") + return os.path.join(app_dir, name) + + +def connect(sock_path): + """chatd's socket: a file on Unix, the matching named pipe on Windows.""" + if sys.platform == "win32": + return open("\\\\.\\pipe\\" + sock_path, "r+b", buffering=0) + stream = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + stream.settimeout(5) + stream.connect(sock_path) + return stream + + +def write_all(stream, data): + view = memoryview(data) + while view: + written = stream.write(view) + if not written: + raise RuntimeError("chatd's socket took nothing") + view = view[written:] + + +class Chat: + def __init__(self, sock_path): + self.stream = connect(sock_path) + + def ask(self, request): + body = json.dumps(request, separators=(",", ":")).encode() + write_all(self.stream, struct.pack("!I", len(body)) + body) + head = b"" + while len(head) < 4: + got = self.stream.read(4 - len(head)) + if not got: + raise RuntimeError("chatd closed its socket") + head += got + length = struct.unpack("!I", head)[0] + if length > 1024 * 1024: + raise RuntimeError("answer exceeds the protocol size limit") + chunks = b"" + while len(chunks) < length: + got = self.stream.read(length - len(chunks)) + if not got: + raise RuntimeError("chatd closed its socket mid-frame") + chunks += got + return json.loads(chunks) + + def close(self): + try: + self.stream.close() + except OSError: + pass + + +def main(): + global STEPS + if not OUT or not APP: + print("E2E_OUT and E2E_APP_DIR are required", file=sys.stderr) + return 1 + os.makedirs(OUT, exist_ok=True) + STEPS = os.path.join(OUT, "steps.jsonl") + open(STEPS, "w", encoding="utf-8").close() + binary = app_bin(APP) + if not os.path.isfile(binary): + step("chatd is in E2E_APP_DIR", False) + return 1 + + data = os.path.join(OUT, "data") + os.makedirs(data, exist_ok=True) + sock_path = os.path.join(data, "chat.sock") + control = os.path.join(data, "telegram.ctl") + open(control, "a", encoding="utf-8").close() + env = os.environ.copy() + for name in list(env): + if name.startswith("TINYCLIENT_SESSION_") or name in KNOBS: + del env[name] + env["TINYCLIENT_DIR"] = data + env["TINYCLIENT_TELEGRAM_FAKE"] = "30" + # Yesterday's midnight UTC, as tests/telegram.rs: the Inbox leaves out a chat nobody + # touched for thirty days. + env["TINYCLIENT_TELEGRAM_T0"] = str(int(time.time()) // 86_400 * 86_400 - 86_400) + # The wire holds this file's pieces until the driver says `file-go`. + env["TINYCLIENT_TELEGRAM_FILE_HOLD"] = "1" + env["TINYCLIENT_SESSION_TELEGRAM"] = SESSION + kwargs = {"cwd": data, "env": env, "stdin": subprocess.DEVNULL} + if sys.platform == "win32": + kwargs["creationflags"] = 0x08000000 + with open(os.path.join(OUT, "chatd.out.log"), "w", encoding="utf-8") as out, open(os.path.join(OUT, "chatd.err.log"), "w", encoding="utf-8") as err: + kwargs["stdout"] = out + kwargs["stderr"] = err + proc = subprocess.Popen([binary], **kwargs) + chat = None + try: + deadline = time.time() + 15 + while chat is None: + if proc.poll() is not None: + step("chatd stays up for the driver", False) + return 1 + if time.time() > deadline: + step("chatd opens its socket", False) + return 1 + try: + chat = Chat(sock_path) + except OSError: + time.sleep(0.1) + drive(chat, control, data) + finally: + if chat: + chat.close() + proc.kill() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + pass + return 1 if FAILED else 0 + + +def key(id): + return {"network": "telegram", "account": ME, "id": id} + + +def name_of(file_id): + """The name chatd keeps a media file under: FNV-1a of its id (blobs::name_of).""" + value = 0xCBF29CE484222325 + for byte in file_id.encode("utf-8"): + value = ((value ^ byte) * 0x100000001B3) & 0xFFFFFFFFFFFFFFFF + return "%016x" % value + + +def wait(what, chat, look, seconds=20): + deadline = time.time() + seconds + while time.time() < deadline: + found = look() + if found is not None: + step(what, True) + return found + time.sleep(0.2) + step(what, False) + return None + + +def steer(control, line): + with open(control, "a", encoding="utf-8") as handle: + handle.write(line + "\n") + + +def ask(chat, request): + try: + return chat.ask(request) + except Exception: + return None + + +def messages(chat, id): + answer = ask(chat, {"op": "messages", "conversation": key(id), "page": "newest", "limit": 100}) + return (answer or {}).get("messages", []) + + +def drive(chat, control, data): + # The scripted wire writes what it is asked there, one line per request. + calls = os.path.join(data, "telegram.calls") + # Where chatd keeps the file while it downloads (blobs::path_of, with the part's extension). + part = os.path.join(data, "media", "telegram", ME, name_of(FILE) + ".part") + + def asked(start): + try: + with open(calls, encoding="utf-8") as handle: + lines = [line.strip() for line in handle] + except OSError: + return 0 + return sum(1 for line in lines if line.startswith(start)) + + def fetch(): + answer = ask(chat, {"op": "fetch", "account": ACCOUNT, "ids": [FILE]}) + files = (answer or {}).get("files") or [] + return files[0] if files else {} + + def accounts(): + return (ask(chat, {"op": "status"}) or {}).get("accounts") or [] + + status = wait("chatd answers its status", chat, lambda: ask(chat, {"op": "status"})) + if status is None: + return + wait("Telegram is connected", chat, lambda: (any(a["link"] == "connected" for a in accounts()) or None)) + wait("the fake's chat is known", chat, lambda: (ask(chat, {"op": "conversation", "conversation": key("u7003")}) or {}).get("conversation")) + + # The chat is open, as the shell opens it. + ask(chat, {"op": "watch", "watching": {"conversation": key(CHAT)}}) + wait("the chat's history is read", chat, lambda: next((m for m in messages(chat, CHAT) if m["id"] == "12"), None)) + + # The file arrives, and the user opens it: Telegram is asked for its first piece, which the + # wire holds, so this is a download in progress. + steer(control, "big-file") + wait("the chat holds the file", chat, lambda: next((m for m in messages(chat, CHAT) if m["id"] == "31" and m.get("attachments") and m["attachments"][0]["file"]["id"] == FILE), None)) + step("the file is not on disk when it is asked for", "path" not in fetch()) + wait("Telegram is asked for the file's first piece, which the wire holds", chat, lambda: asked("GetFile document 9400 at 0") or None) + wait("the download keeps a part file", chat, lambda: os.path.exists(part) or None) + pieces = asked("GetFile document 9400 at") + + # The shell stops it, as its cancel does, and the wire lets its piece go. + answer = ask(chat, {"op": "cancel_download", "account": ACCOUNT, "id": FILE}) + step("chatd takes the request to stop the download", bool(answer) and answer.get("op") == "ok") + steer(control, "file-go") + wait("the part file is gone", chat, lambda: (not os.path.exists(part)) or None) + step("Telegram is not asked for the rest of the file", asked("GetFile document 9400 at") == pieces) + file = fetch() + step("nothing landed and nothing failed", "path" not in file and "failed" not in file) + + # Asking for it again is a new download: it starts over and ends on disk, whole. + def on_disk(): + return fetch().get("path") or None + + path = wait("asking for the file again lands it", chat, on_disk) + if path is not None: + with open(path, "rb") as handle: + step("the file holds the bytes Telegram served", handle.read() == bytes(at % 251 for at in range(FILE_BYTES))) + step("it was fetched from the start, as a second download", asked("GetFile document 9400 at 0") == 2) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/e2e/scenarios/telegram-cancel-download/drive.windows.ps1 b/e2e/scenarios/telegram-cancel-download/drive.windows.ps1 new file mode 100644 index 00000000..6178be08 --- /dev/null +++ b/e2e/scenarios/telegram-cancel-download/drive.windows.ps1 @@ -0,0 +1,17 @@ +# telegram-cancel-download on Windows. The lab runs this in the console session it is already filming. +$ErrorActionPreference = 'Stop' +$drive = Join-Path $PSScriptRoot 'drive.py' +if (Get-Command py -ErrorAction SilentlyContinue) { + & py -3 $drive + exit $LASTEXITCODE +} +if (Get-Command python -ErrorAction SilentlyContinue) { + & python $drive + exit $LASTEXITCODE +} +if (Get-Command python3 -ErrorAction SilentlyContinue) { + & python3 $drive + exit $LASTEXITCODE +} +Write-Host 'python is not on PATH (tried py -3, python, python3)' +exit 1 diff --git a/e2e/scenarios/telegram-cancel-download/scenario.json b/e2e/scenarios/telegram-cancel-download/scenario.json new file mode 100644 index 00000000..b82d430e --- /dev/null +++ b/e2e/scenarios/telegram-cancel-download/scenario.json @@ -0,0 +1,12 @@ +{ + "id": "telegram-cancel-download", + "title": "Stopping a Telegram download ends it at the piece on its way and leaves no part file behind", + "platforms": ["windows", "macos", "linux"], + "not_applicable": { + "android": "The lab's phone demo build bypasses chatd and cannot run the scripted Telegram wire.", + "ios": "The lab's phone demo build bypasses chatd and cannot run the scripted Telegram wire." + }, + "needs": [], + "release": false, + "max_still_seconds": 60 +}