Take the transfers the engine does itself out of the TeamSpeak connection
voice.rs handled Download, Upload and CancelTransfer with a copying task per transfer, a progress cadence, the picture limits and a cancel table; none of it is reachable since SessionLink copies the bytes itself over the connections OpenRead and OpenWrite open (the picture limits and the negotiation deadline live there, tested in link/tests.rs). The connection keeps the two connection jobs and refuses the three commands in words; files::upload and its close wait go with it (SessionLink uses upload_to, and the TCP test of the upload runs through that), and the test of the picture download time moves to the cache, which owns the function. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1edc52ce74
commit
d70a3582f2
3 files changed
+31
-278
No files matched your search
@@ -500,6 +500,15 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn large_pictures_get_time_to_arrive() {
|
||||
let secs = std::time::Duration::from_secs;
|
||||
assert_eq!(image_download_time(0), secs(60));
|
||||
assert_eq!(image_download_time(100 << 10), secs(72));
|
||||
// The largest picture, at the slowest rate allowed.
|
||||
assert_eq!(image_download_time(MAX_PICTURE_BYTES), secs(60 + 16384));
|
||||
}
|
||||
|
||||
fn temp_dir(tag: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"voelin-cache-{tag}-{}-{:?}",
|
||||
|
||||
@@ -254,29 +254,6 @@ async fn receive<R: AsyncRead + Unpin>(
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a server may take to close a transfer connection after the last
|
||||
/// byte before the upload counts as done anyway.
|
||||
const CLOSE_WAIT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// Send `file` from `offset` (`size` bytes in total) over `stream`, a
|
||||
/// connection the server closes once it has everything. Reports `Started`,
|
||||
/// `Progress` and the final state.
|
||||
pub(crate) async fn upload<S: AsyncRead + AsyncWrite + Unpin>(
|
||||
stream: S,
|
||||
file: PathBuf,
|
||||
size: u64,
|
||||
offset: u64,
|
||||
progress_every: Duration,
|
||||
report: Report,
|
||||
) {
|
||||
let (mut read, write) = tokio::io::split(stream);
|
||||
let closed = async move {
|
||||
let _ = tokio::time::timeout(CLOSE_WAIT, read.read(&mut [0u8; 1])).await;
|
||||
Ok(())
|
||||
};
|
||||
upload_to(write, closed, file, size, offset, progress_every, report).await;
|
||||
}
|
||||
|
||||
/// Send `file` from `offset` (`size` bytes in total) into `writer`, then end
|
||||
/// it and wait for `stored`, which resolves once the server has the file.
|
||||
/// Reports `Started`, `Progress` and the final state.
|
||||
@@ -592,7 +569,8 @@ mod tests {
|
||||
});
|
||||
let (report, states) = recorder();
|
||||
let stream = TcpStream::connect(addr).await.unwrap();
|
||||
upload(stream, file.clone(), 10, 4, Duration::ZERO, report).await;
|
||||
let (_, write) = tokio::io::split(stream);
|
||||
upload_to(write, async { Ok(()) }, file.clone(), 10, 4, Duration::ZERO, report).await;
|
||||
assert_eq!(server.await.unwrap(), b"456789");
|
||||
assert!(matches!(states.lock().unwrap().last(), Some(TransferState::Done { .. })));
|
||||
assert_eq!(md5_file(&file).unwrap(), "781e5e245d69b566979b86e28d23f2c7");
|
||||
|
||||
@@ -14,14 +14,12 @@
|
||||
//! gateway directory, our own stream's life ([`LinkEvent::OwnStream`]).
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use base64::Engine as _;
|
||||
use futures::prelude::*;
|
||||
use tokio::sync::{mpsc, oneshot, watch};
|
||||
use tokio::task::AbortHandle;
|
||||
use tokio::time::{Instant, timeout};
|
||||
use tracing::{debug, info, warn};
|
||||
use tsclientlib::events::Event as BookEvent;
|
||||
@@ -38,11 +36,9 @@ use voelin_stream::{ClientState, Request, StreamNotification};
|
||||
|
||||
use super::book::presence_from_book;
|
||||
use super::ts_link::{ConnectOptions, Watches};
|
||||
use crate::cache::{self, IMAGE_NEGOTIATION, image_download_time};
|
||||
use crate::files::{self, FileEntry, Report, RequestId, Sink, TransferId, TransferState};
|
||||
use crate::files::{self, FileEntry, RequestId};
|
||||
use crate::link::{BoxDuplex, BoxRead, LinkCmd, LinkCtx, LinkEvent, Remote};
|
||||
use crate::offline::{OfflineMessage, OfflineMessageInfo};
|
||||
use crate::settings::FILES_PROGRESS_MS;
|
||||
use crate::stream::{StreamCmd, StreamHandle, StreamInput};
|
||||
use crate::{BackendInfo, Event, JoinFailure, POKE_MESSAGE_MAX};
|
||||
|
||||
@@ -158,24 +154,13 @@ enum Pending {
|
||||
Quiet,
|
||||
}
|
||||
|
||||
/// A transfer the server has not opened yet.
|
||||
/// A transfer connection the server has not opened yet: the caller wants the
|
||||
/// connection itself, and does the copying (the engine's `SessionLink`
|
||||
/// does, with its progress, its limits and its cancel).
|
||||
enum Job {
|
||||
Download {
|
||||
transfer: Option<TransferId>,
|
||||
offset: u64,
|
||||
sink: Sink,
|
||||
report: Report,
|
||||
started: Instant,
|
||||
},
|
||||
Upload {
|
||||
transfer: Option<TransferId>,
|
||||
from: PathBuf,
|
||||
size: u64,
|
||||
report: Report,
|
||||
},
|
||||
/// The caller wants the connection itself ([`LinkCmd::OpenRead`]).
|
||||
/// [`LinkCmd::OpenRead`].
|
||||
OpenRead(oneshot::Sender<Result<(u64, BoxRead), String>>),
|
||||
/// The caller wants the connection itself ([`LinkCmd::OpenWrite`]).
|
||||
/// [`LinkCmd::OpenWrite`].
|
||||
OpenWrite(oneshot::Sender<Result<(u64, BoxDuplex), String>>),
|
||||
}
|
||||
|
||||
@@ -183,9 +168,6 @@ impl Job {
|
||||
/// The job could not be done: tell whoever waits.
|
||||
fn fail(self, text: String) {
|
||||
match self {
|
||||
Job::Download { report, .. } | Job::Upload { report, .. } => {
|
||||
report(TransferState::Failed(text));
|
||||
}
|
||||
Job::OpenRead(reply) => {
|
||||
let _ = reply.send(Err(text));
|
||||
}
|
||||
@@ -194,43 +176,6 @@ impl Job {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The user cancelled the transfer before the server opened it.
|
||||
fn cancel(self) {
|
||||
if let Job::Download { report, .. } | Job::Upload { report, .. } = self {
|
||||
report(TransferState::Cancelled);
|
||||
}
|
||||
}
|
||||
|
||||
fn transfer(&self) -> Option<TransferId> {
|
||||
match self {
|
||||
Job::Download { transfer, .. } | Job::Upload { transfer, .. } => *transfer,
|
||||
Job::OpenRead(_) | Job::OpenWrite(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bound background image handshakes without imposing a deadline on user transfers.
|
||||
fn expire_image_jobs(jobs: &mut HashMap<FiletransferHandle, Job>, now: Instant) {
|
||||
let expired: Vec<FiletransferHandle> = jobs
|
||||
.iter()
|
||||
.filter(|(_, job)| {
|
||||
matches!(job, Job::Download { transfer: None, started, .. }
|
||||
if now.duration_since(*started) >= IMAGE_NEGOTIATION)
|
||||
})
|
||||
.map(|(handle, _)| *handle)
|
||||
.collect();
|
||||
for handle in expired {
|
||||
if let Some(job) = jobs.remove(&handle) {
|
||||
job.fail("image transfer negotiation timed out".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A user's transfer, for cancelling.
|
||||
enum Slot {
|
||||
Waiting(FiletransferHandle),
|
||||
Running { task: AbortHandle, part: Option<PathBuf>, report: Report },
|
||||
}
|
||||
|
||||
/// Run a voice connection until it ends or is told to disconnect.
|
||||
@@ -279,7 +224,6 @@ struct Voice {
|
||||
talking: HashMap<u16, Instant>,
|
||||
pending: HashMap<MessageHandle, Pending>,
|
||||
jobs: HashMap<FiletransferHandle, Job>,
|
||||
transfers: HashMap<TransferId, Slot>,
|
||||
/// `updatemytsdata` is to be sent once connected again: a reconnect
|
||||
/// (tsclientlib's own) leaves the server without it.
|
||||
myts_data_due: bool,
|
||||
@@ -411,7 +355,6 @@ async fn run_inner(
|
||||
talking: HashMap::new(),
|
||||
pending: HashMap::new(),
|
||||
jobs: HashMap::new(),
|
||||
transfers: HashMap::new(),
|
||||
myts_data_due: false,
|
||||
myts_shown: tsclientlib::MytsData::default(),
|
||||
streams,
|
||||
@@ -573,7 +516,6 @@ impl Voice {
|
||||
}
|
||||
|
||||
fn tick(&mut self) {
|
||||
expire_image_jobs(&mut self.jobs, Instant::now());
|
||||
let events = &self.events;
|
||||
self.talking.retain(|client, last| {
|
||||
let active = last.elapsed() < Duration::from_millis(400);
|
||||
@@ -584,10 +526,6 @@ impl Voice {
|
||||
});
|
||||
}
|
||||
|
||||
fn progress_every(&self) -> Duration {
|
||||
Duration::from_millis(self.link.settings.current().get(&FILES_PROGRESS_MS).into())
|
||||
}
|
||||
|
||||
fn item(&mut self, item: StreamItem) -> anyhow::Result<()> {
|
||||
match item {
|
||||
StreamItem::BookEvents(book_events) => {
|
||||
@@ -626,73 +564,24 @@ impl Voice {
|
||||
}
|
||||
}
|
||||
}
|
||||
// The server opened a transfer connection: the caller that asked for it
|
||||
// gets the connection itself.
|
||||
StreamItem::FileDownload(handle, download) => {
|
||||
if matches!(self.jobs.get(&handle), Some(Job::OpenRead(_))) {
|
||||
// The caller wants the connection itself.
|
||||
if let Some(Job::OpenRead(reply)) = self.jobs.remove(&handle) {
|
||||
let _ = reply.send(Ok((download.size, Box::pin(download.stream))));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(Job::Download { transfer, offset, sink, report, .. }) =
|
||||
self.jobs.remove(&handle)
|
||||
if matches!(self.jobs.get(&handle), Some(Job::OpenRead(_)))
|
||||
&& let Some(Job::OpenRead(reply)) = self.jobs.remove(&handle)
|
||||
{
|
||||
// Pictures (avatars, icons, banners): bounded like the
|
||||
// banners on the web, the user's own files are not.
|
||||
if transfer.is_none() && download.size > cache::MAX_PICTURE_BYTES {
|
||||
let limit = cache::MAX_PICTURE_BYTES >> 20;
|
||||
report(TransferState::Failed(format!("larger than {limit} MiB")));
|
||||
return Ok(());
|
||||
}
|
||||
let part = sink.part().map(ToOwned::to_owned);
|
||||
let progress = self.progress_every();
|
||||
let task_report = report.clone();
|
||||
let deadline = image_download_time(download.size);
|
||||
let task = tokio::spawn(async move {
|
||||
let receive = files::download(
|
||||
download.stream,
|
||||
download.size,
|
||||
offset,
|
||||
sink,
|
||||
progress,
|
||||
task_report.clone(),
|
||||
);
|
||||
if transfer.is_some() {
|
||||
receive.await;
|
||||
} else if timeout(deadline, receive).await.is_err() {
|
||||
task_report(TransferState::Failed("image download timed out".into()));
|
||||
}
|
||||
});
|
||||
self.running(transfer, task.abort_handle(), part, report);
|
||||
let _ = reply.send(Ok((download.size, Box::pin(download.stream))));
|
||||
}
|
||||
}
|
||||
StreamItem::FileUpload(handle, upload) => {
|
||||
if matches!(self.jobs.get(&handle), Some(Job::OpenWrite(_))) {
|
||||
// The caller wants the connection itself.
|
||||
if let Some(Job::OpenWrite(reply)) = self.jobs.remove(&handle) {
|
||||
let _ = reply.send(Ok((upload.seek_position, Box::pin(upload.stream))));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(Job::Upload { transfer, from, size, report }) =
|
||||
self.jobs.remove(&handle)
|
||||
if matches!(self.jobs.get(&handle), Some(Job::OpenWrite(_)))
|
||||
&& let Some(Job::OpenWrite(reply)) = self.jobs.remove(&handle)
|
||||
{
|
||||
let task = tokio::spawn(files::upload(
|
||||
upload.stream,
|
||||
from,
|
||||
size,
|
||||
upload.seek_position,
|
||||
self.progress_every(),
|
||||
report.clone(),
|
||||
));
|
||||
self.running(transfer, task.abort_handle(), None, report);
|
||||
let _ = reply.send(Ok((upload.seek_position, Box::pin(upload.stream))));
|
||||
}
|
||||
}
|
||||
StreamItem::FiletransferFailed(handle, error) => {
|
||||
if let Some(job) = self.jobs.remove(&handle) {
|
||||
if let Some(id) = job.transfer() {
|
||||
self.transfers.remove(&id);
|
||||
}
|
||||
job.fail(transfer_error(&error));
|
||||
}
|
||||
}
|
||||
@@ -707,22 +596,6 @@ impl Voice {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn running(
|
||||
&mut self,
|
||||
transfer: Option<TransferId>,
|
||||
task: AbortHandle,
|
||||
part: Option<PathBuf>,
|
||||
report: Report,
|
||||
) {
|
||||
self.transfers.retain(|_, slot| match slot {
|
||||
Slot::Running { task, .. } => !task.is_finished(),
|
||||
Slot::Waiting(_) => true,
|
||||
});
|
||||
if let Some(id) = transfer {
|
||||
self.transfers.insert(id, Slot::Running { task, part, report });
|
||||
}
|
||||
}
|
||||
|
||||
/// A chat message or poke from the book.
|
||||
fn message(&self, target: &MessageTarget, invoker: &tsclientlib::Invoker, text: &str) {
|
||||
let uid = invoker.uid.as_ref().map(|u| u.as_ref().to_string());
|
||||
@@ -1104,57 +977,6 @@ impl Voice {
|
||||
Pending::FileList { request, channel: dir.channel, path, entries: Vec::new() };
|
||||
self.send(cmd, pending)?;
|
||||
}
|
||||
LinkCmd::Download { transfer, file, sink, report } => {
|
||||
let offset = sink.offset();
|
||||
let seek = (offset > 0).then_some(offset);
|
||||
let password = file.password.as_deref().filter(|p| !p.is_empty());
|
||||
let channel = tsclientlib::ChannelId(file.channel);
|
||||
let handle = match self.con.download_file(channel, &file.path, password, seek) {
|
||||
Ok(handle) => handle,
|
||||
Err(e) => {
|
||||
report(TransferState::Failed(e.to_string()));
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
report(TransferState::Requested);
|
||||
self.jobs.insert(
|
||||
handle,
|
||||
Job::Download { transfer, offset, sink, report, started: Instant::now() },
|
||||
);
|
||||
if let Some(id) = transfer {
|
||||
self.transfers.insert(id, Slot::Waiting(handle));
|
||||
}
|
||||
}
|
||||
LinkCmd::Upload { transfer, file, from, overwrite, resume, report } => {
|
||||
let size = match std::fs::metadata(&from) {
|
||||
Ok(m) if m.is_file() => m.len(),
|
||||
Ok(_) => {
|
||||
report(TransferState::Failed(format!("{} is not a file", from.display())));
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) => {
|
||||
report(TransferState::Failed(format!("{}: {e}", from.display())));
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
let password = file.password.as_deref().filter(|p| !p.is_empty());
|
||||
let channel = tsclientlib::ChannelId(file.channel);
|
||||
let handle = match self
|
||||
.con
|
||||
.upload_file(channel, &file.path, password, size, overwrite, resume)
|
||||
{
|
||||
Ok(handle) => handle,
|
||||
Err(e) => {
|
||||
report(TransferState::Failed(e.to_string()));
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
report(TransferState::Requested);
|
||||
self.jobs.insert(handle, Job::Upload { transfer, from, size, report });
|
||||
if let Some(id) = transfer {
|
||||
self.transfers.insert(id, Slot::Waiting(handle));
|
||||
}
|
||||
}
|
||||
LinkCmd::OpenRead { file, offset, reply } => {
|
||||
let seek = (offset > 0).then_some(offset);
|
||||
let password = file.password.as_deref().filter(|p| !p.is_empty());
|
||||
@@ -1180,21 +1002,12 @@ impl Voice {
|
||||
}
|
||||
}
|
||||
}
|
||||
LinkCmd::CancelTransfer(id) => match self.transfers.remove(&id) {
|
||||
Some(Slot::Waiting(handle)) => {
|
||||
if let Some(job) = self.jobs.remove(&handle) {
|
||||
job.cancel();
|
||||
}
|
||||
}
|
||||
Some(Slot::Running { task, part, report }) if !task.is_finished() => {
|
||||
task.abort();
|
||||
if let Some(part) = part {
|
||||
let _ = std::fs::remove_file(part);
|
||||
}
|
||||
report(TransferState::Cancelled);
|
||||
}
|
||||
_ => debug!(id, "cancel: no such transfer (finished?)"),
|
||||
},
|
||||
// SessionLink copies the bytes itself, over the connections OpenRead and
|
||||
// OpenWrite open (`docs/session-seam.md` section 8): this link is never
|
||||
// given a transfer to run.
|
||||
LinkCmd::Download { .. } | LinkCmd::Upload { .. } | LinkCmd::CancelTransfer(_) => {
|
||||
anyhow::bail!("this link does not run transfers itself");
|
||||
}
|
||||
LinkCmd::DeleteFiles { request, channel, password, paths } => {
|
||||
let cpw = encode_password(password.as_deref());
|
||||
let mut parts = paths.iter().map(|p| c2s::OutDeleteFilePart {
|
||||
@@ -1559,52 +1372,6 @@ mod poke_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod image_download_tests {
|
||||
use super::*;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[test]
|
||||
fn stalled_image_handshake_expires_but_user_transfer_does_not() {
|
||||
let started = Instant::now();
|
||||
let reports = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = reports.clone();
|
||||
let report: Report = Arc::new(move |state| sink.lock().unwrap().push(state));
|
||||
let mut jobs = HashMap::new();
|
||||
for (id, transfer) in [(1, None), (2, Some(77))] {
|
||||
jobs.insert(
|
||||
FiletransferHandle(id),
|
||||
Job::Download {
|
||||
transfer,
|
||||
offset: 0,
|
||||
sink: Sink::Memory,
|
||||
report: report.clone(),
|
||||
started,
|
||||
},
|
||||
);
|
||||
}
|
||||
expire_image_jobs(&mut jobs, started + IMAGE_NEGOTIATION - Duration::from_secs(1));
|
||||
assert_eq!(jobs.len(), 2);
|
||||
assert!(reports.lock().unwrap().is_empty());
|
||||
expire_image_jobs(&mut jobs, started + IMAGE_NEGOTIATION);
|
||||
assert_eq!(jobs.len(), 1);
|
||||
assert!(jobs.contains_key(&FiletransferHandle(2)));
|
||||
assert!(
|
||||
matches!(&reports.lock().unwrap()[..], [TransferState::Failed(error)] if error.contains("timed out"))
|
||||
);
|
||||
expire_image_jobs(&mut jobs, started + Duration::from_secs(60));
|
||||
assert_eq!(reports.lock().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_pictures_get_time_to_arrive() {
|
||||
assert_eq!(image_download_time(0), Duration::from_secs(60));
|
||||
assert_eq!(image_download_time(100 << 10), Duration::from_secs(72));
|
||||
// The largest picture, at the slowest rate allowed.
|
||||
assert_eq!(image_download_time(cache::MAX_PICTURE_BYTES), Duration::from_secs(60 + 16384));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod account_tests {
|
||||
use super::*;
|
||||
@@ -1752,7 +1519,6 @@ mod account_tests {
|
||||
talking: HashMap::new(),
|
||||
pending: HashMap::new(),
|
||||
jobs: HashMap::new(),
|
||||
transfers: HashMap::new(),
|
||||
myts_data_due: false,
|
||||
myts_shown: tsclientlib::MytsData::default(),
|
||||
streams: None,
|
||||
|
||||
Reference in new issue
Block a user