Merge main (3930ef2) into phase5/ui-vm-2
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
commit
4491ecee25
21 files changed
+820
-198
No files matched your search
@@ -199,19 +199,22 @@ async fn receive<R: AsyncRead + Unpin>(
|
||||
let mut done = offset;
|
||||
match sink {
|
||||
Sink::File { part, dest, append } => {
|
||||
// The directory and the file are made in one step, without a pause in
|
||||
// which the task could be stopped: a cancel stops the task, waits for
|
||||
// it and then removes the part file, so what the task made must be
|
||||
// there by then (a pending open on the blocking pool would not be).
|
||||
if let Some(dir) = part.parent().filter(|d| !d.as_os_str().is_empty()) {
|
||||
tokio::fs::create_dir_all(dir)
|
||||
.await
|
||||
.map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
}
|
||||
let mut file = tokio::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.write(true)
|
||||
.append(*append)
|
||||
.truncate(!*append)
|
||||
.open(part)
|
||||
.await
|
||||
.map_err(|e| format!("{}: {e}", part.display()))?;
|
||||
let mut file = tokio::fs::File::from_std(
|
||||
std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.write(true)
|
||||
.append(*append)
|
||||
.truncate(!*append)
|
||||
.open(part)
|
||||
.map_err(|e| format!("{}: {e}", part.display()))?,
|
||||
);
|
||||
let received = async {
|
||||
while done < size {
|
||||
let n = stream.read(&mut buf).await.map_err(|e| e.to_string())?;
|
||||
|
||||
@@ -77,7 +77,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::task::AbortHandle;
|
||||
use tokio::task::JoinHandle;
|
||||
use tracing::{debug, info, warn};
|
||||
use voelin_audio::EncodedVoice;
|
||||
use voelin_model::replica::{Replica, SCHEMA_GENERATION, ScopeId};
|
||||
@@ -325,7 +325,7 @@ async fn drive(
|
||||
|
||||
/// A transfer a user can cancel.
|
||||
struct Running {
|
||||
task: AbortHandle,
|
||||
task: JoinHandle<()>,
|
||||
part: Option<PathBuf>,
|
||||
report: Report,
|
||||
/// The server has opened it (a part file may exist).
|
||||
@@ -1479,7 +1479,7 @@ impl Conn {
|
||||
receive.await;
|
||||
}
|
||||
});
|
||||
self.running(transfer, Running { task: task.abort_handle(), part, report, started });
|
||||
self.running(transfer, Running { task, part, report, started });
|
||||
}
|
||||
|
||||
fn upload(
|
||||
@@ -1560,7 +1560,7 @@ impl Conn {
|
||||
let stored = async move { done.await.map(|_| ()).map_err(|e| text(&e, false)) };
|
||||
files::upload_to(body, stored, from, size, offset, progress, task_report).await;
|
||||
});
|
||||
self.running(transfer, Running { task: task.abort_handle(), part: None, report, started });
|
||||
self.running(transfer, Running { task, part: None, report, started });
|
||||
}
|
||||
|
||||
fn running(&mut self, transfer: Option<TransferId>, running: Running) {
|
||||
@@ -1572,15 +1572,21 @@ impl Conn {
|
||||
|
||||
fn cancel(&mut self, id: TransferId) {
|
||||
match self.transfers.remove(&id) {
|
||||
Some(running) if !running.task.is_finished() => {
|
||||
running.task.abort();
|
||||
// A part file exists once the server has opened the transfer.
|
||||
if running.started.load(Ordering::Acquire)
|
||||
&& let Some(part) = running.part
|
||||
{
|
||||
let _ = std::fs::remove_file(part);
|
||||
}
|
||||
(running.report)(TransferState::Cancelled);
|
||||
Some(Running { task, part, report, started }) if !task.is_finished() => {
|
||||
task.abort();
|
||||
// The part file goes once the task has stopped, not at once: the task
|
||||
// opens it in one step (files::download), so it is there or it never
|
||||
// will be, and a removal that came before the open would leave it.
|
||||
tokio::spawn(async move {
|
||||
let _ = task.await;
|
||||
// A part file exists once the server has opened the transfer.
|
||||
if started.load(Ordering::Acquire)
|
||||
&& let Some(part) = part
|
||||
{
|
||||
let _ = std::fs::remove_file(part);
|
||||
}
|
||||
report(TransferState::Cancelled);
|
||||
});
|
||||
}
|
||||
_ => debug!(id, "cancel: no such transfer (finished?)"),
|
||||
}
|
||||
|
||||
@@ -607,6 +607,12 @@ async fn a_file_is_downloaded_through_the_connection_the_link_opens() {
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert!(
|
||||
states.lock().unwrap().iter().any(|s| matches!(s, TransferState::Started { .. })),
|
||||
"the transfer started: {:?}",
|
||||
states.lock().unwrap()
|
||||
);
|
||||
// Cancelled the moment it is Started, when its part file may be opening.
|
||||
rig.give(LinkCmd::CancelTransfer(3));
|
||||
assert_eq!(final_state(&states).await, TransferState::Cancelled);
|
||||
rig.quiet();
|
||||
@@ -1956,20 +1962,38 @@ async fn a_scope_bigger_than_the_channel_is_sent_in_bigger_chunks() {
|
||||
const CHANNELS: u64 = 5_000;
|
||||
let (conns, mut seen) = mpsc::unbounded_channel();
|
||||
let connector = LinkConnector::new(Arc::new(Recorder(conns)), &["ts3server"]);
|
||||
let (mut params, _media) = connect_params("ts3server://fake.test?port=9987");
|
||||
let (mut params, mut media) = connect_params("ts3server://fake.test?port=9987");
|
||||
params.credential = Credential::Foreign { kind: "teamspeak", blob: Default::default() };
|
||||
params.push_capacity = 1;
|
||||
let connecting = tokio::spawn(connector.connect(params));
|
||||
let inner = within("the link to be asked", seen.recv()).await;
|
||||
inner.events.send(connected(everything())).unwrap();
|
||||
// Made before the link is told it is connected: the connector waits only
|
||||
// 250 ms for the first snapshot, and making 5,000 channels can take longer
|
||||
// than that on a busy machine, which left the session without them.
|
||||
let mut big = presence();
|
||||
for id in 100..100 + CHANNELS {
|
||||
let channel = ChannelInfo { id, name: format!("c{id}"), ..Default::default() };
|
||||
big.channels.insert(id, channel);
|
||||
}
|
||||
inner.events.send(connected(everything())).unwrap();
|
||||
inner.events.send(LinkEvent::Presence(Box::new(big))).unwrap();
|
||||
let connected = within("a session", async { connecting.await.ok().and_then(Result::ok) }).await;
|
||||
let (session, mut pushes) = (connected.session, connected.pushes);
|
||||
// The scope is sent whole only if the presence is in the host's state when
|
||||
// it is asked for. The link takes its events in order, and a voice packet
|
||||
// of one of the presence's clients comes through only once the presence
|
||||
// is in: the packet says it is.
|
||||
inner
|
||||
.events
|
||||
.send(LinkEvent::Audio(VoicePacket {
|
||||
talker: TalkerId(8),
|
||||
seq: 1,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: OPUS_20_MS.to_vec(),
|
||||
}))
|
||||
.unwrap();
|
||||
within("the voice", media.recv()).await;
|
||||
|
||||
let server = ScopeId::Server(1);
|
||||
session.request(subscribe(server)).await.unwrap();
|
||||
@@ -2178,12 +2202,48 @@ async fn event_of<T>(
|
||||
.await
|
||||
}
|
||||
|
||||
/// Asks for the file list of the lobby until the answer is one `wanted` takes,
|
||||
/// one question at a time: the next goes out only when the last is answered.
|
||||
/// Asked every few milliseconds instead, the answers fell behind the 16
|
||||
/// events the bus holds (and the host's work), and the one that counted was
|
||||
/// lost in the backlog.
|
||||
async fn ask_files_until(
|
||||
cmd_tx: &mpsc::UnboundedSender<LinkCmd>,
|
||||
bus: &mut broadcast::Receiver<Event>,
|
||||
request: &mut crate::files::RequestId,
|
||||
wanted: impl Fn(&Result<Vec<FileEntry>, String>) -> bool,
|
||||
) {
|
||||
within("the file list to be answered as wanted", async {
|
||||
loop {
|
||||
*request += 1;
|
||||
let dir = remote(10, None, "/");
|
||||
cmd_tx.send(LinkCmd::ListFiles { request: *request, dir }).ok()?;
|
||||
let result = loop {
|
||||
match bus.recv().await {
|
||||
Ok(Event::FileList { request: answered, result, .. })
|
||||
if answered == *request =>
|
||||
{
|
||||
break result;
|
||||
}
|
||||
Ok(_) | Err(broadcast::error::RecvError::Lagged(_)) => {}
|
||||
Err(broadcast::error::RecvError::Closed) => return None,
|
||||
}
|
||||
};
|
||||
if wanted(&result) {
|
||||
return Some(());
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
/// `Server.features` narrows what the host offers (protocol 1.3,
|
||||
/// `docs/session-seam.md` 4.7), and a `HostUpdate` changes what is narrowed.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_features_of_a_server_are_the_hosts_narrowed_by_the_servers_list() {
|
||||
use v1::entity::Kind;
|
||||
use voelin_proto::test_util::{FakeConnector, eventually};
|
||||
use voelin_proto::test_util::FakeConnector;
|
||||
|
||||
let connector = FakeConnector::new();
|
||||
let host = connector.host();
|
||||
@@ -2235,55 +2295,26 @@ async fn the_features_of_a_server_are_the_hosts_narrowed_by_the_servers_list() {
|
||||
})
|
||||
.count()
|
||||
};
|
||||
let ask = |request| {
|
||||
let dir = remote(10, None, "/");
|
||||
cmd_tx.send(LinkCmd::ListFiles { request, dir }).unwrap();
|
||||
};
|
||||
let refusal = "not offered by this server: files";
|
||||
let refused =
|
||||
|event: &Event| matches!(event, Event::FileList { result: Err(why), .. } if why == refusal);
|
||||
|result: &Result<Vec<FileEntry>, String>| matches!(result, Err(why) if why == refusal);
|
||||
let mut request = 0;
|
||||
|
||||
// Refused here: nothing reaches the host.
|
||||
ask(1);
|
||||
loop {
|
||||
let event = within("the refusal", async { bus.recv().await.ok() }).await;
|
||||
if refused(&event) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
ask_files_until(&cmd_tx, &mut bus, &mut request, refused).await;
|
||||
assert_eq!(file_lists(), 0);
|
||||
|
||||
// The server lifts its list (an empty one keeps all the host's): files work.
|
||||
put_server(&[]);
|
||||
let mut request = 1;
|
||||
eventually(WAIT, "a file list to reach the host", || {
|
||||
request += 1;
|
||||
ask(request);
|
||||
file_lists() > 0
|
||||
})
|
||||
.await;
|
||||
ask_files_until(&cmd_tx, &mut bus, &mut request, |result| !refused(result)).await;
|
||||
assert!(file_lists() > 0, "the answer did not come from the host");
|
||||
|
||||
// The host narrows what it offers this user. A refusal counts only for a
|
||||
// request made after the update: the earlier ones were answered by the host's
|
||||
// wider set (or, before the server lifted its list, refused for that).
|
||||
// The host narrows what it offers this user. Every question is answered
|
||||
// before the next is asked, so those asked from here on are the ones the
|
||||
// update can refuse; the earlier ones were answered by the host's wider set.
|
||||
let update = v1::HostUpdate { features: vec!["voice".into(), "chat".into()], limits: None };
|
||||
handle.push(v1::Push { body: Some(v1::push::Body::HostUpdate(update)) }).unwrap();
|
||||
let after = request;
|
||||
within("the narrower set to apply", async {
|
||||
loop {
|
||||
request += 1;
|
||||
ask(request);
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
while let Ok(event) = bus.try_recv() {
|
||||
if matches!(&event, Event::FileList { request, .. } if *request > after)
|
||||
&& refused(&event)
|
||||
{
|
||||
return Some(());
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
ask_files_until(&cmd_tx, &mut bus, &mut request, refused).await;
|
||||
}
|
||||
|
||||
/// A port that is no port is refused in words, not dropped: the connection
|
||||
|
||||
+111
-38
@@ -3257,9 +3257,13 @@ impl LocalPreview {
|
||||
}
|
||||
|
||||
/// The first and last column of the rectangle in the middle row of a
|
||||
/// decoded test pattern. Checks that pixels further than two columns from
|
||||
/// its edges (which the codec blurs) have the colour of the rectangle or
|
||||
/// the background.
|
||||
/// decoded test pattern, after checking the row's structure: background, one
|
||||
/// run of the rectangle, background. A pixel is whichever of the pattern's two
|
||||
/// colours it is nearer to; it is not asked to be within some distance of one,
|
||||
/// because an encoder that falls behind lowers its quality (the VP8 speed
|
||||
/// control of the streamer does) and then moves a flat colour by 30 and more
|
||||
/// per channel, still nowhere near the other colour. The two columns at each
|
||||
/// edge, which the codec blurs, may be either.
|
||||
#[cfg(all(test, feature = "media-desktop"))]
|
||||
pub(crate) fn rectangle_span(picture: &VideoFrame) -> (u32, u32) {
|
||||
use voelin_media::capture::synthetic::{BACKGROUND, RECT_COLOR};
|
||||
@@ -3270,15 +3274,23 @@ pub(crate) fn rectangle_span(picture: &VideoFrame) -> (u32, u32) {
|
||||
let i = ((y * picture.width + x) * 4) as usize;
|
||||
[rgba[i], rgba[i + 1], rgba[i + 2]]
|
||||
};
|
||||
let close = |p: [u8; 3], c: [u8; 3]| p.iter().zip(c).all(|(a, b)| a.abs_diff(b) <= 24);
|
||||
let inside: Vec<u32> = (0..picture.width).filter(|&x| close(pixel(x), RECT_COLOR)).collect();
|
||||
let (&a, &b) = inside.first().zip(inside.last()).expect("no rectangle in the middle row");
|
||||
for x in 0..picture.width {
|
||||
if x + 2 < a || x > b + 2 {
|
||||
assert!(close(pixel(x), BACKGROUND), "pixel {x},{y} is {:?}", pixel(x));
|
||||
} else if (a + 2..=b.saturating_sub(2)).contains(&x) {
|
||||
assert!(close(pixel(x), RECT_COLOR), "pixel {x},{y} is {:?}", pixel(x));
|
||||
}
|
||||
let distance = |p: [u8; 3], c: [u8; 3]| -> u32 {
|
||||
p.iter().zip(c).map(|(a, b)| u32::from(a.abs_diff(b)).pow(2)).sum()
|
||||
};
|
||||
let rectangle = |x: u32| {
|
||||
let p = pixel(x);
|
||||
distance(p, RECT_COLOR) < distance(p, BACKGROUND)
|
||||
};
|
||||
let a = (0..picture.width).find(|&x| rectangle(x)).expect("no rectangle in the middle row");
|
||||
let b = (0..picture.width).rfind(|&x| rectangle(x)).unwrap();
|
||||
// One run: everything between its ends, but the blurred edges, is the
|
||||
// rectangle's. Whatever is outside is the background by the choice of a and b.
|
||||
for x in a + 2..=b.saturating_sub(2) {
|
||||
assert!(
|
||||
rectangle(x),
|
||||
"pixel {x},{y} is {:?}, in the middle of the rectangle (columns {a} to {b})",
|
||||
pixel(x)
|
||||
);
|
||||
}
|
||||
(a, b)
|
||||
}
|
||||
@@ -3536,11 +3548,30 @@ mod tests {
|
||||
};
|
||||
told(30).await;
|
||||
assert_eq!(streamer.bitrate_kbps(), 1105);
|
||||
// Not per frame.
|
||||
let count = lock(&sink.formats).len();
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert_eq!(lock(&sink.formats).len(), count);
|
||||
assert_eq!(streamer.stats().layers[0].bitrate, auto_bitrate(640, 480, 30));
|
||||
// Not per frame. The sink is told when it is attached and again by the
|
||||
// encoder before its first frame (the same format twice), so the count is
|
||||
// taken once a frame has been handed over and compared after more have;
|
||||
// the frames, not a pause, are what "per frame" counts.
|
||||
let frames_by = |frames: u64| {
|
||||
let streamer = &streamer;
|
||||
async move {
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while streamer.stats().layers[0].frames < frames {
|
||||
assert!(Instant::now() < deadline, "{frames} frames: {:?}", streamer.stats());
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
};
|
||||
frames_by(1).await;
|
||||
let (count, seen) = (lock(&sink.formats).len(), streamer.stats().layers[0].frames);
|
||||
frames_by(seen + 5).await;
|
||||
assert_eq!(lock(&sink.formats).len(), count, "told again within five frames");
|
||||
// The stats follow the sink's being told, not the other way round.
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while streamer.stats().layers[0].bitrate != auto_bitrate(640, 480, 30) {
|
||||
assert!(Instant::now() < deadline, "{:?}", streamer.stats().layers);
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
let update = StreamerConfigUpdate { fps: Some(15), ..StreamerConfigUpdate::default() };
|
||||
streamer.reconfigure(&codecs, update).unwrap();
|
||||
told(15).await;
|
||||
@@ -3711,15 +3742,35 @@ mod tests {
|
||||
assert!((60..=68).contains(&(b - a + 1)), "{spans:?}");
|
||||
}
|
||||
assert_ne!(spans.first(), spans.last(), "the rectangle moves");
|
||||
let stats = preview.stats();
|
||||
assert!(stats.decoded >= 10 && stats.error.is_none(), "{stats:?}");
|
||||
assert_eq!(stats.codec, Some(Codec::Vp8));
|
||||
let (before_first, first) = (Instant::now(), preview.stats());
|
||||
let after_first = Instant::now();
|
||||
assert!(first.decoded >= 10 && first.error.is_none(), "{first:?}");
|
||||
assert_eq!(first.codec, Some(Codec::Vp8));
|
||||
assert_eq!(preview.streamer().backend(), "synthetic");
|
||||
// Rates over the second since: the pattern's rate, its bitrate.
|
||||
// The rates are the counters over the time since the call before. How
|
||||
// long that was the test does not say (a busy machine stretches a second,
|
||||
// and the rate of pictures it manages is not what is tested), but it lies
|
||||
// between the two spans the test timed around it.
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
let stats = preview.stats();
|
||||
assert!((20..=40).contains(&stats.fps), "{stats:?}");
|
||||
assert!((100_000..5_000_000).contains(&stats.bitrate), "{stats:?}");
|
||||
let before_second = Instant::now();
|
||||
let second = preview.stats();
|
||||
let after_second = Instant::now();
|
||||
let longest = after_second.duration_since(before_first).as_secs_f64();
|
||||
let shortest = before_second.duration_since(after_first).as_secs_f64();
|
||||
let frames = (second.decoded - first.decoded) as f64;
|
||||
let bits = (second.bytes - first.bytes) as f64 * 8.0;
|
||||
assert!(frames > 0.0, "no picture in the second: {first:?} {second:?}");
|
||||
// (The pictures per second are rounded, the bits per second cut off.)
|
||||
let fps = f64::from(second.fps);
|
||||
assert!(
|
||||
(frames / longest - 0.5..=frames / shortest + 0.5).contains(&fps),
|
||||
"{frames} pictures in {shortest} to {longest} s are not {fps} a second"
|
||||
);
|
||||
let bitrate = second.bitrate as f64;
|
||||
assert!(
|
||||
(bits / longest - 1.0..=bits / shortest).contains(&bitrate),
|
||||
"{bits} bits in {shortest} to {longest} s are not {bitrate} a second"
|
||||
);
|
||||
}
|
||||
|
||||
/// A VP8 decoder for the pipeline tests: fails (with errors, or giving
|
||||
@@ -4143,7 +4194,8 @@ mod tests {
|
||||
};
|
||||
let streamer = Streamer::start(&codecs, config).await.unwrap();
|
||||
let wait = |what: &str, done: &dyn Fn(&StreamerStats) -> bool| {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
// What is waited for is a state; the deadline only ends a hang.
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
let stats = streamer.stats();
|
||||
if done(&stats) {
|
||||
@@ -4153,15 +4205,18 @@ mod tests {
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
};
|
||||
// The SineSource tone is 0.05; the second at half gain.
|
||||
// The SineSource tone is 0.05; the second at half gain. The sources are metered
|
||||
// before the mixer has made anything of them: the mix and the state of the
|
||||
// sources are waited for too, not taken to be there with the meters.
|
||||
let near = |level: f32, want: f32| (level - want).abs() < want * 0.1;
|
||||
let stats = wait("both tones", &|s| {
|
||||
let stats = wait("both tones, mixed", &|s| {
|
||||
s.audio_sources.len() == 2
|
||||
&& near(s.audio_sources[0].level.peak, 0.05)
|
||||
&& near(s.audio_sources[1].level.peak, 0.025)
|
||||
&& s.audio_sources.iter().all(|s| s.state == SourceState::Playing)
|
||||
&& s.audio_level.peak > 0.05
|
||||
&& s.audio_limiter == 1.0
|
||||
});
|
||||
assert!(stats.audio_sources.iter().all(|s| s.state == SourceState::Playing));
|
||||
assert!(stats.audio_level.peak > 0.05 && stats.audio_limiter == 1.0, "{stats:?}");
|
||||
let first = stats.audio_sources[0].id;
|
||||
|
||||
// Mute the first (kept: same id), drop the second, add the
|
||||
@@ -4177,19 +4232,31 @@ mod tests {
|
||||
streamer.reconfigure(&codecs, update).unwrap();
|
||||
assert_eq!(streamer.audio_sources().len(), 3);
|
||||
let publisher = tap::publisher_id();
|
||||
let speak = std::thread::spawn(move || {
|
||||
// 20 ms of a 0.2 tone every 20 ms, for a second.
|
||||
let chunk: Vec<f32> = (0..960).map(|i| 0.2 * (i as f32 * 0.1).sin()).collect();
|
||||
for _ in 0..50 {
|
||||
tap::microphone().publish(publisher, &chunk);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
let heard = Arc::new(AtomicBool::new(false));
|
||||
let speak = std::thread::spawn({
|
||||
let heard = heard.clone();
|
||||
move || {
|
||||
// 20 ms of a 0.2 tone every 20 ms, until the test has heard it: the
|
||||
// source takes what is published only from when it runs, which a
|
||||
// busy machine delays by any time (the cap ends a thread whose test
|
||||
// failed first).
|
||||
let cap = Instant::now() + Duration::from_secs(120);
|
||||
let chunk: Vec<f32> = (0..960).map(|i| 0.2 * (i as f32 * 0.1).sin()).collect();
|
||||
while !heard.load(Ordering::Relaxed) && Instant::now() < cap {
|
||||
tap::microphone().publish(publisher, &chunk);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
}
|
||||
});
|
||||
let stats = wait("microphone in, tone muted", &|s| {
|
||||
s.audio_sources.len() == 3
|
||||
&& s.audio_sources[1].level.peak > 0.15
|
||||
&& s.audio_level.peak > 0.15
|
||||
&& s.audio_sources[2].error.as_deref().is_some_and(|e| e.contains("no window"))
|
||||
// Muted, and still metered: the tone's own level is read again.
|
||||
&& near(s.audio_sources[0].level.peak, 0.05)
|
||||
});
|
||||
heard.store(true, Ordering::Relaxed);
|
||||
speak.join().unwrap();
|
||||
assert_eq!(stats.audio_sources[0].id, first, "the kept tone keeps its source");
|
||||
assert!(stats.audio_sources[0].spec.muted);
|
||||
@@ -4221,9 +4288,15 @@ mod tests {
|
||||
assert!(streamer.has_audio(), "{:?}", streamer.audio_error());
|
||||
let mut source = EncodedSource::new(streamer);
|
||||
let mut frames = Vec::new();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while frames.iter().filter(|f: &&EncodedFrame| f.kind == MediaKind::Audio).count() < 10 {
|
||||
assert!(Instant::now() < deadline, "no audio");
|
||||
// Ten frames of audio and one of video, whichever the encoders make first:
|
||||
// 20 ms of audio is quickly made, and a busy machine can keep the video
|
||||
// encoder from its first frame for longer than that. The deadline only ends
|
||||
// a hang.
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
let count =
|
||||
|frames: &[EncodedFrame], kind| frames.iter().filter(|f| f.kind == kind).count();
|
||||
while count(&frames, MediaKind::Audio) < 10 || count(&frames, MediaKind::Video) < 1 {
|
||||
assert!(Instant::now() < deadline, "no audio or no video in {} frames", frames.len());
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
source.poll_frames(Instant::now(), &mut frames);
|
||||
}
|
||||
|
||||
@@ -1295,9 +1295,21 @@ mod tests {
|
||||
// Before the viewer asks: its offer is made after this.
|
||||
sink.layer_format(0, format(60_000_000));
|
||||
handles[1].send(StreamCmd::Watch { stream_id: "s-1".into() });
|
||||
wait(&mut rx, |e| match e {
|
||||
Event::WatchState { session: 2, state: WatchState::Connected, .. } => Some(()),
|
||||
_ => None,
|
||||
// Connected for the viewer and for the streamer, in either order: the
|
||||
// streamer asks for a keyframe when its viewer connects, a moment after
|
||||
// the viewer has seen the connection.
|
||||
let (mut watching, mut served) = (false, false);
|
||||
wait(&mut rx, |e| {
|
||||
match e {
|
||||
Event::WatchState { session: 2, state: WatchState::Connected, .. } => {
|
||||
watching = true;
|
||||
}
|
||||
Event::StreamViewers { session: 1, viewers } => {
|
||||
served |= viewers.iter().any(|v| v.state == ViewerState::Connected);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
(watching && served).then_some(())
|
||||
})
|
||||
.await;
|
||||
// 3840x2160 at 60 fps is level 5.2 (0x34) in both profiles.
|
||||
@@ -1312,7 +1324,15 @@ mod tests {
|
||||
sink.take_layer_keyframes(&mut layers);
|
||||
layers.contains(0)
|
||||
};
|
||||
keyframes();
|
||||
// What asked for a keyframe so far (going live, the viewer's connecting
|
||||
// and its first picture request) is done when a moment longer than the
|
||||
// merging interval of requests (250 ms) passes with none.
|
||||
for _ in 0..50 {
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
if !keyframes() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
sink.layer_format(0, format(9_000_000));
|
||||
timeout(Duration::from_secs(5), async {
|
||||
while !keyframes() {
|
||||
@@ -1322,7 +1342,11 @@ mod tests {
|
||||
.await
|
||||
.expect("the layer did not change");
|
||||
sink.layer_format(0, format(9_000_000));
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
// The stream task takes its commands in order: its answer to this one
|
||||
// (an error, nobody is viewer 65535) comes after all that the format
|
||||
// above set going, and nothing is left to wait out.
|
||||
handles[0].send(StreamCmd::Kick { viewer: u16::MAX });
|
||||
wait(&mut rx, |e| matches!(e, Event::Error { session: 1, .. }).then_some(())).await;
|
||||
assert!(!keyframes(), "nothing changed");
|
||||
handles[0].send(StreamCmd::Stop);
|
||||
}
|
||||
@@ -1701,7 +1725,16 @@ mod tests {
|
||||
let stats = pipeline.stats();
|
||||
assert_eq!(stats.codec, Some(Codec::Vp8));
|
||||
assert!(stats.error.is_none(), "{stats:?}");
|
||||
let sent = streamer.stats();
|
||||
// The encoder counts a frame once the sink has taken it, so the picture
|
||||
// can be at the viewer before the count has moved.
|
||||
let mut sent = streamer.stats();
|
||||
for _ in 0..500 {
|
||||
if sent.video_frames >= 15 && sent.audio_frames > 0 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
sent = streamer.stats();
|
||||
}
|
||||
assert!(sent.video_frames >= 15 && sent.audio_frames > 0, "{sent:?}");
|
||||
|
||||
handles[0].send(StreamCmd::Stop);
|
||||
|
||||
@@ -259,7 +259,8 @@ pub fn from_blob(blob: &IdentityBlob) -> Result<Identity, IdentityError> {
|
||||
}
|
||||
|
||||
/// The TeamSpeak identity in `json`, the text [`to_blob`] writes and the key
|
||||
/// store keeps; every reader of that text refuses it through here.
|
||||
/// store keeps; voelin-core reads that text only through here (voelin-store
|
||||
/// parses it too, for its own checks of a stored row).
|
||||
///
|
||||
/// What does not read is refused in words that say how it is wrong
|
||||
/// (malformed, cut short, not an identity, unreadable) and where (line and
|
||||
|
||||
@@ -1650,8 +1650,10 @@ mod account_tests {
|
||||
events,
|
||||
));
|
||||
let mut packet = [0; 2048];
|
||||
let (_, first) =
|
||||
timeout(Duration::from_secs(5), server.recv_from(&mut packet)).await.unwrap().unwrap();
|
||||
let (_, first) = timeout(Duration::from_secs(5), server.recv_from(&mut packet))
|
||||
.await
|
||||
.expect("the first handshake packet within 5 s")
|
||||
.unwrap();
|
||||
// A logout/clear notification must cancel the old socket and restart.
|
||||
account.send_replace(None);
|
||||
let second = timeout(Duration::from_secs(5), async {
|
||||
@@ -1663,11 +1665,14 @@ mod account_tests {
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
.expect("a handshake packet from a new socket within 5 s of the account change");
|
||||
assert_ne!(first, second);
|
||||
// Losing the account authority fails closed immediately, not after connect timeout.
|
||||
drop(account);
|
||||
timeout(Duration::from_secs(2), task).await.unwrap().unwrap();
|
||||
timeout(Duration::from_secs(2), task)
|
||||
.await
|
||||
.expect("the connection to end within 2 s of the account source closing")
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(received.recv().await, Some(LinkEvent::Disconnected(Some(reason))) if reason == "account source closed")
|
||||
);
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
//! What more than one integration test of this crate needs (a test binary
|
||||
//! that uses it declares `mod common;`).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Wait until nothing has the SQLite database at `path` open any more, as when
|
||||
/// the process that had it has ended: SQLite deletes the write-ahead log
|
||||
/// (`<path>-wal`) when the last connection closes.
|
||||
///
|
||||
/// A dropped `Engine` is not that yet. Its task ends later, the history writer
|
||||
/// is joined there, and closing the connection checkpoints the log under an
|
||||
/// exclusive lock, with fsyncs. A connection opened meanwhile waits for the
|
||||
/// lock only as long as the busy timeout (5 s) and then fails with
|
||||
/// `DatabaseBusy`, which a loaded disk makes happen (with every fsync taking
|
||||
/// 6 s it happens every time).
|
||||
pub async fn closed(path: &Path) {
|
||||
let mut wal = path.as_os_str().to_owned();
|
||||
wal.push("-wal");
|
||||
let wal = PathBuf::from(wal);
|
||||
tokio::time::timeout(Duration::from_secs(120), async {
|
||||
while wal.exists() {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("the engine's database connection closed");
|
||||
}
|
||||
@@ -24,6 +24,8 @@ use voelin_gateway_proto::{
|
||||
};
|
||||
use voelin_model::{ChatMessage, ChatTarget, PresenceSnapshot};
|
||||
|
||||
mod common;
|
||||
|
||||
const LOBBY: ChatTarget = ChatTarget::Channel(1);
|
||||
const ME: &str = "me-uid";
|
||||
|
||||
@@ -529,6 +531,8 @@ async fn history_on_open_paging_and_offline_messages() {
|
||||
assert_eq!(texts(&stored), ["m1", "m2", "m3", "m4", "m5", "while away 1", "while away 2"]);
|
||||
history.flush();
|
||||
drop((engine, history));
|
||||
// Dropping the engine does not close the database yet (see `closed`).
|
||||
common::closed(&path).await;
|
||||
|
||||
// After a restart, with the gateway down: the stored page, found by the
|
||||
// gateway's URL, which is remembered with the server's id.
|
||||
@@ -812,7 +816,16 @@ async fn not_found_proxy() -> String {
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_next_published_gateway_is_used_when_one_fails() {
|
||||
let proxy = not_found_proxy().await;
|
||||
let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
|
||||
// A port that is taken and never listened on: connecting is refused at once,
|
||||
// and no other test of this process can be given it meanwhile (one that was
|
||||
// only free for a moment could be, the listeners of the others bind port 0).
|
||||
let reserved = tokio::net::TcpSocket::new_v4().unwrap();
|
||||
reserved.bind("127.0.0.1:0".parse().unwrap()).unwrap();
|
||||
let closed = reserved.local_addr().unwrap().port();
|
||||
assert!(
|
||||
tokio::net::TcpStream::connect(("127.0.0.1", closed)).await.is_err(),
|
||||
"something listens on port {closed}"
|
||||
);
|
||||
let gw = FakeGateway::start().await;
|
||||
let path = temp_db("fallback");
|
||||
let engine = Engine::start_with(Settings::in_memory(), History::open(&path).unwrap());
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
//! Engine against the development servers (dev/docker-compose.yml).
|
||||
//! Runs only with `VOELIN_LIVE=1`; `scripts/it-smoke.sh` sets it.
|
||||
|
||||
use std::sync::LazyLock;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::sync::RwLock;
|
||||
use tokio::sync::broadcast::Receiver;
|
||||
use tokio::time::{Instant, timeout_at};
|
||||
use voelin_core::{
|
||||
@@ -15,6 +17,17 @@ fn live() -> bool {
|
||||
std::env::var("VOELIN_LIVE").is_ok_and(|v| v == "1")
|
||||
}
|
||||
|
||||
/// The TeamSpeak 6 server's banners are the server's, and `ts6_banners` sets and
|
||||
/// unsets them there. While it does, whatever else connects to the server is
|
||||
/// told the addresses of those banners, and an engine fetches what it is told
|
||||
/// (as it should): the requests of such an engine reached the HTTP server of
|
||||
/// `ts6_banners`, which counts the requests of the engine under test, and the
|
||||
/// test failed on `disabled policy must prevent HTTP requests` in every run
|
||||
/// that had the tests of this file run side by side (as they do). The tests
|
||||
/// that connect to the server hold this shared, `ts6_banners` exclusively: it
|
||||
/// runs with the server to itself, and the others before or after it.
|
||||
static TS6: LazyLock<RwLock<()>> = LazyLock::new(|| RwLock::new(()));
|
||||
|
||||
/// Wait for an event matching `f`, failing after 20 s.
|
||||
async fn wait_for(
|
||||
rx: &mut Receiver<Event>,
|
||||
@@ -131,6 +144,7 @@ async fn ts6_engine() {
|
||||
if !live() {
|
||||
return;
|
||||
}
|
||||
let _server = TS6.read().await;
|
||||
engine_roundtrip("127.0.0.1:9988", query(voelin_query::Transport::Ssh, "127.0.0.1:10022"))
|
||||
.await;
|
||||
}
|
||||
@@ -258,6 +272,7 @@ async fn ts6_channel_joins() {
|
||||
if !live() {
|
||||
return;
|
||||
}
|
||||
let _server = TS6.read().await;
|
||||
channel_joins("127.0.0.1:9988", query(voelin_query::Transport::Ssh, "127.0.0.1:10022")).await;
|
||||
}
|
||||
|
||||
@@ -329,6 +344,7 @@ async fn ts6_banners() {
|
||||
if !live() {
|
||||
return;
|
||||
}
|
||||
let _server = TS6.write().await;
|
||||
let voice_addr =
|
||||
std::env::var("VOELIN_BANNER_VOICE_ADDR").unwrap_or_else(|_| "127.0.0.1:9988".into());
|
||||
let query_addr =
|
||||
@@ -512,6 +528,7 @@ async fn ts6_avatars() {
|
||||
if !live() {
|
||||
return;
|
||||
}
|
||||
let _server = TS6.read().await;
|
||||
let voice_addr =
|
||||
std::env::var("VOELIN_BANNER_VOICE_ADDR").unwrap_or_else(|_| "127.0.0.1:9988".into());
|
||||
let dir = std::env::temp_dir().join(format!("voelin-live-avatars-{}", std::process::id()));
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
//! in the client database). The round trips against real servers are in
|
||||
//! `scripts/it-smoke.sh` (`voelinctl engine`).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::sync::broadcast;
|
||||
@@ -11,6 +10,10 @@ use voelin_core::settings::Settings;
|
||||
use voelin_core::{Command, Contact, DownloadTo, Engine, Event, History, Relation, TransferState};
|
||||
use voelin_model::FileRef;
|
||||
|
||||
mod common;
|
||||
|
||||
use common::closed;
|
||||
|
||||
async fn next<T>(rx: &mut broadcast::Receiver<Event>, mut f: impl FnMut(Event) -> Option<T>) -> T {
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
@@ -23,29 +26,6 @@ async fn next<T>(rx: &mut broadcast::Receiver<Event>, mut f: impl FnMut(Event) -
|
||||
.expect("event in time")
|
||||
}
|
||||
|
||||
/// Wait until nothing has the SQLite database at `path` open any more, as when
|
||||
/// the process that had it has ended: SQLite deletes the write-ahead log
|
||||
/// (`<path>-wal`) when the last connection closes.
|
||||
///
|
||||
/// A dropped `Engine` is not that yet. Its task ends later, the history writer
|
||||
/// is joined there, and closing the connection checkpoints the log under an
|
||||
/// exclusive lock, with fsyncs. A connection opened meanwhile waits for the
|
||||
/// lock only as long as the busy timeout (5 s) and then fails with
|
||||
/// `DatabaseBusy`, which a loaded disk makes happen (with every fsync taking
|
||||
/// 6 s it happens every time).
|
||||
async fn closed(path: &Path) {
|
||||
let mut wal = path.as_os_str().to_owned();
|
||||
wal.push("-wal");
|
||||
let wal = PathBuf::from(wal);
|
||||
tokio::time::timeout(Duration::from_secs(120), async {
|
||||
while wal.exists() {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("the engine's database connection closed");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn requests_without_voice_fail_with_their_ids() {
|
||||
let engine = Engine::start();
|
||||
|
||||
@@ -1180,19 +1180,32 @@ mod tests {
|
||||
scenes
|
||||
}
|
||||
|
||||
/// The first preview frame that `wanted` takes. The preview keeps the latest
|
||||
/// frame only, so few older ones are waiting or on their way: the number of
|
||||
/// frames looked at is the bound (the work), and the wait for each, which a
|
||||
/// busy machine can stretch, only ends a hang.
|
||||
fn preview_until(
|
||||
preview: &Handoff<VideoFrame>,
|
||||
wanted: impl Fn(&VideoFrame) -> bool,
|
||||
) -> Arc<VideoFrame> {
|
||||
for _ in 0..20 {
|
||||
let frame = preview.wait_timeout(Duration::from_secs(30)).expect("a preview frame");
|
||||
if wanted(&frame) {
|
||||
return frame;
|
||||
}
|
||||
}
|
||||
panic!("the preview never showed what was asked for");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn it_composes_into_the_preview_and_follows_commands() {
|
||||
let studio = Studio::start(one_colour_scene()).await.unwrap();
|
||||
let preview = studio.preview();
|
||||
studio.apply(Command::SetPreview { width: 32, height: 24, fps: 60 }).await.unwrap();
|
||||
let started = Instant::now();
|
||||
let frame = loop {
|
||||
if let Some(frame) = preview.wait_timeout(Duration::from_millis(200)) {
|
||||
break frame;
|
||||
}
|
||||
assert!(started.elapsed() < Duration::from_secs(5), "no preview frame");
|
||||
};
|
||||
assert_eq!((frame.width, frame.height), (32, 24));
|
||||
// The studio composes from the moment it starts, at the size and rate the
|
||||
// preview has then (480x270, 15 fps): a frame of that size can be the
|
||||
// first one there is.
|
||||
let frame = preview_until(&preview, |f| (f.width, f.height) == (32, 24));
|
||||
let crate::frame::FrameData::Rgba(p) = &frame.data else { panic!("not RGBA") };
|
||||
assert_eq!(&p.data[..4], &[9, 8, 7, 255]);
|
||||
|
||||
@@ -1211,15 +1224,12 @@ mod tests {
|
||||
.unwrap();
|
||||
studio.apply(Command::SetActiveScene { scene: break_id }).await.unwrap();
|
||||
assert_eq!(studio.status().active_scene, break_id);
|
||||
// The new scene's source draws.
|
||||
let frame = loop {
|
||||
let frame = preview.wait_timeout(Duration::from_secs(2)).expect("a preview frame");
|
||||
let crate::frame::FrameData::Rgba(p) = &frame.data else { panic!() };
|
||||
if p.data[..3] == [1, 2, 3] {
|
||||
break frame;
|
||||
}
|
||||
assert!(started.elapsed() < Duration::from_secs(10), "the scene never switched");
|
||||
};
|
||||
// The new scene's source draws, from the first frame composed after the
|
||||
// command.
|
||||
let frame = preview_until(
|
||||
&preview,
|
||||
|f| matches!(&f.data, crate::frame::FrameData::Rgba(p) if p.data[..3] == [1, 2, 3]),
|
||||
);
|
||||
drop(frame);
|
||||
|
||||
studio.apply(Command::RemoveScene { scene: break_id }).await.unwrap();
|
||||
@@ -1402,9 +1412,16 @@ mod tests {
|
||||
assert_eq!((listed[0].width, listed[0].height), (64, 48));
|
||||
let frames = capture.start(&SourceId::Studio, &CaptureOptions::default()).await.unwrap();
|
||||
let mut frames = frames;
|
||||
let frame = frames.recv_timeout(Duration::from_secs(5)).expect("a composed frame");
|
||||
// (The wait only ends a hang.)
|
||||
let frame = frames.recv_timeout(Duration::from_secs(30)).expect("a composed frame");
|
||||
assert_eq!((frame.width, frame.height), (64, 48));
|
||||
assert!(studio.shared.delivered.load(Ordering::Relaxed) > 0);
|
||||
// A frame is counted once it has been handed over, so the count can still be
|
||||
// behind when the frame is in the hands of the test.
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while studio.shared.delivered.load(Ordering::Relaxed) == 0 {
|
||||
assert!(Instant::now() < deadline, "the frame handed over was never counted");
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
capture.stop();
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
@@ -350,7 +350,22 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn an_unwritable_path_fails_at_once() {
|
||||
assert!(Recorder::start("/nonexistent-root-dir/x/clip.webm", 0, 2).is_err());
|
||||
assert!(Recorder::start("clip.mp4", 0, 2).is_err());
|
||||
let dir = dir("unwritable");
|
||||
// A path below a regular file fails for every user, root included
|
||||
// (ENOTDIR). A directory that is merely missing would be created, and
|
||||
// a read-only one is written to by root.
|
||||
let file = dir.join("not-a-directory");
|
||||
std::fs::write(&file, b"x").unwrap();
|
||||
assert!(Recorder::start(file.join("x").join("clip.webm"), 0, 2).is_err());
|
||||
// The directory is there and the file cannot be created because the
|
||||
// path names a directory (EISDIR, again for every user).
|
||||
let named_like_a_file = dir.join("clip.webm");
|
||||
std::fs::create_dir(&named_like_a_file).unwrap();
|
||||
assert!(Recorder::start(&named_like_a_file, 0, 2).is_err());
|
||||
// A name that asks for no known container is refused before any file
|
||||
// is created.
|
||||
assert!(Recorder::start(dir.join("clip.mp4"), 0, 2).is_err());
|
||||
assert!(!dir.join("clip.mp4").exists());
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
}
|
||||
@@ -85,6 +85,11 @@ fn on_a_bus_of_its_own() {
|
||||
let text =
|
||||
format!("{}{}", String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr));
|
||||
if run.status.success() {
|
||||
// A child that ran no test (its filter matched nothing) exits 0 as well.
|
||||
assert!(
|
||||
text.contains("test result: ok. 1 passed;"),
|
||||
"the run on its own bus exited 0 without reporting `1 passed`:\n{text}"
|
||||
);
|
||||
return;
|
||||
}
|
||||
// The test ran and failed, or the bus never came up.
|
||||
|
||||
Reference in new issue
Block a user