Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions crates/chatd/src/adapters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1914,6 +1914,11 @@ pub enum Command {
ids: Vec<String>,
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<String> },
/// A stage hand, an accepted invite, or a moderator moving someone.
Expand Down
7 changes: 7 additions & 0 deletions crates/chatd/src/adapters/telegram.rs
Original file line number Diff line number Diff line change
Expand Up @@ -804,6 +804,13 @@ pub fn start(ctx: Context, session: &str, inbox: Receiver<Command>) -> 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);
}
Expand Down
14 changes: 11 additions & 3 deletions crates/chatd/src/adapters/telegram/fake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Condvar>,
Expand Down Expand Up @@ -2329,10 +2330,17 @@ impl Fake {
// asked again until the `peer-go`.
(self.hold_pages && asked::<f::messages::GetDialogs>(body).is_some_and(|request| !matches!(request.offset_peer, tl::enums::InputPeer::Empty)) && !world.dialogs_go)
|| (self.hold_peer_dialogs && asked::<f::messages::GetPeerDialogs>(body).is_some() && !world.peer_go)
|| (self.hold_files && asked::<f::upload::GetFile>(body).is_some_and(|request| is_ridge_thumb(&request.location)) && !world.file_go)
|| (self.hold_files && asked::<f::upload::GetFile>(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")
Expand Down
116 changes: 107 additions & 9 deletions crates/chatd/src/adapters/telegram/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -93,13 +95,18 @@ enum Job {
Seen(Box<Want>, 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 {
ctx: Context,
jobs: Sender<Job>,
waiting: Arc<AtomicUsize>,
held: Mutex<Held>,
/// 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<Mutex<HashSet<String>>>,
}

/// What the shell may ask for by id, and what it asked for before it was known here.
Expand Down Expand Up @@ -312,15 +319,26 @@ 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 {
/// Starts the thread that fetches. It ends when the adapter's last connection is dropped.
pub fn start(ctx: &Context) -> Files {
let (jobs, inbox) = channel::<Job>();
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.
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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);
Expand All @@ -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<Account>) {
Expand Down Expand Up @@ -478,7 +514,7 @@ impl Files {
let (inline, wants): (Vec<Want>, Vec<Want>) = 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);
}
}
Expand Down Expand Up @@ -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<Job>) {
Expand Down Expand Up @@ -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<i32>) -> 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),
})?;
Expand All @@ -876,8 +929,9 @@ fn write_inline(out: &mut std::fs::File, bytes: &[u8]) -> Result<u64, Fault> {
}

/// 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<u64, Fault>) -> Result<bool, Fault> {
/// 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<u64, Fault>) -> Result<bool, Fault> {
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();
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -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<Aes256>;

/// The counter Telegram's CDN uses: the redirect's IV plus `offset / 16`, big-endian.
Expand Down Expand Up @@ -1070,6 +1134,10 @@ fn download(account: &Account, want: &Want, carried: &mut HashSet<i32>, 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
Expand All @@ -1084,6 +1152,10 @@ fn download(account: &Account, want: &Want, carried: &mut HashSet<i32>, 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),
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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()
}

Expand Down
1 change: 1 addition & 0 deletions crates/chatd/src/demo/adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1515,6 +1515,7 @@ impl Demo {
| Command::Watch(_)
| Command::Wanted(_)
| Command::WantedSpan { .. }
| Command::CancelDownload { .. }
| Command::TelegramCallSignal { .. }
| Command::TelegramAcceptLoginToken { .. }
| Command::TelegramCallSpeaking { .. }
Expand Down
9 changes: 9 additions & 0 deletions crates/chatd/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)];
Expand Down
Loading
Loading