diff --git a/.gitignore b/.gitignore index 004fc92..f3070a4 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,5 @@ /dev/.state/ /dist/ /.cargo/ +# agent scratch of a worktree (the MAO policy in CLAUDE.md) +/.scratch/ diff --git a/crates/voelin-core/src/files.rs b/crates/voelin-core/src/files.rs index d0e416d..8ea23fc 100644 --- a/crates/voelin-core/src/files.rs +++ b/crates/voelin-core/src/files.rs @@ -199,19 +199,22 @@ async fn receive( 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())?; diff --git a/crates/voelin-core/src/link/session_link.rs b/crates/voelin-core/src/link/session_link.rs index c1ecb59..33ada6b 100644 --- a/crates/voelin-core/src/link/session_link.rs +++ b/crates/voelin-core/src/link/session_link.rs @@ -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, 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, 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?)"), } diff --git a/crates/voelin-core/src/link/tests.rs b/crates/voelin-core/src/link/tests.rs index cf41183..711cce5 100644 --- a/crates/voelin-core/src/link/tests.rs +++ b/crates/voelin-core/src/link/tests.rs @@ -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(); diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index 5eb0986..38db2da 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -3540,7 +3540,12 @@ mod tests { 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)); + // 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; diff --git a/crates/voelin-core/src/stream.rs b/crates/voelin-core/src/stream.rs index 585631e..f385e2c 100644 --- a/crates/voelin-core/src/stream.rs +++ b/crates/voelin-core/src/stream.rs @@ -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() { @@ -1701,7 +1721,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); diff --git a/crates/voelin-media/src/studio/output/record.rs b/crates/voelin-media/src/studio/output/record.rs index 29c5cb1..0c78cd3 100644 --- a/crates/voelin-media/src/studio/output/record.rs +++ b/crates/voelin-media/src/studio/output/record.rs @@ -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(); } } diff --git a/docs/ci.md b/docs/ci.md index 61871e7..538eb27 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -46,17 +46,20 @@ the separate `release.yml` workflow below. this label (the left side must match the workflow's `runs-on`): ```text - ubuntu-24.04:docker://ghcr.io/catthehacker/ubuntu:act-24.04 + ubuntu-24.04:docker://docker.gitea.com/runner-images:ubuntu-24.04 ``` Configure this in the runner's labels when registering/configuring it; - an `ubuntu-latest` label alone does not match. The job image must provide - Bash, Git, the OpenSSH client, Node.js for checkout v4, and root or - passwordless sudo for apt. + an `ubuntu-latest` label alone does not match. This is the image of the + runner that runs this repository's CI, and the one the tests are checked + against ([Tests under the job image](#tests-under-the-job-image)). The job + image must provide Bash, Git, the OpenSSH client, Node.js for checkout v4, + and root or passwordless sudo for apt. 3. Allow network access from the runner and job container to the Gitea instance, GitHub (checkout action, dependencies and RustSec advisories), - GHCR (runner image), Ubuntu apt mirrors, rustup distribution servers, - crates.io and dependency/license sources used by cargo-about. The + `docker.gitea.com` (runner image), Ubuntu apt mirrors, rustup + distribution servers, crates.io and dependency/license sources used by + cargo-about. The workspace also depends on the **private** VoelinProtocol repository (`voelin-identity`, over SSH), so the job needs read access to it and the server's SSH port. The workflows set that up themselves from a repository @@ -102,6 +105,86 @@ all step results. Local YAML/shell checks do not prove that a particular Gitea instance, runner registration, network policy or resource allocation can complete this job. +### Tests under the job image + +The test step runs as **root** in an Ubuntu 24.04 container of the +`ubuntu-24.04` label ([Runner setup](#runner-setup): +`docker.gitea.com/runner-images:ubuntu-24.04`, `HOME=/root`) to which only +the apt packages of the system-dependencies action are added. A test that +assumes a developer machine fails there, and a run takes about an hour, so +check a change to the tests the way CI runs them, with every failing test of +every crate listed in one go (`--no-fail-fast`): + +```sh +# A bare clone of the private VoelinProtocol repository (see below the block): +# git clone --bare ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git +: "${PROTOCOL_GIT:?path of a bare clone of VoelinProtocol}" +# Root owns what the container writes: keep it in a directory of its own +# (.scratch/ is in .gitignore; see below the block for its removal). +mkdir -p .scratch +docker run --rm --init -v "$PWD":/src -w /src -e HOME=/root \ + -v "$PROTOCOL_GIT":/protocol.git:ro -e CARGO_NET_GIT_FETCH_WITH_CLI=true \ + -e CARGO_HOME=/src/.scratch/cargo -e RUSTUP_HOME=/src/.scratch/rustup \ + -e CARGO_TARGET_DIR=/src/.scratch/target \ + docker.gitea.com/runner-images:ubuntu-24.04 bash -c ' + git -C / config --global url."file:///protocol.git".insteadOf \ + ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git + apt-get update && apt-get install -y --no-install-recommends \ + build-essential ca-certificates cmake curl git jq pkg-config python3 \ + libasound2-dev libfontconfig1-dev libxkbcommon-dev libvpx-dev \ + libdav1d-dev libpipewire-0.3-dev libspa-0.2-dev libclang-dev xvfb xauth + curl --proto =https --tlsv1.2 -sSf https://sh.rustup.rs | \ + sh -s -- -y --profile minimal --default-toolchain none + . "$CARGO_HOME/env" && rustup toolchain install + xvfb-run -a bash -c "VOELIN_X11_TEST_DISPLAY=\$DISPLAY \ + cargo test --workspace --locked --no-fail-fast"' +``` + +`--init` is required: `bash -c` runs its last command, `xvfb-run`, as the +container's process 1, and that never gets to start `cargo` (the command +hangs). The runner starts its steps with `docker exec` in a container whose +process 1 is something else, so CI itself is not affected. + +The private VoelinProtocol dependency needs the deploy key +([below](#voelinprotocol-access)). The block reads it from a local bare clone +instead: `PROTOCOL_GIT` is mounted at `/protocol.git` and git is told to use +it in place of the SSH URL (with `CARGO_NET_GIT_FETCH_WITH_CLI=true`, as in CI, +so that cargo runs the `git` command), which leaves `Cargo.lock` as it is. +The `git config` is run with `-C /` because a git worktree's `.git` file points +outside the mount, and `git config` in `/src` then fails with `fatal: not a git +repository: (null)` (exit 128). To use the deploy key instead, set it up as +described below and leave out the `PROTOCOL_GIT` lines and the `git config` +command. What the container wrote under `.scratch/` belongs to root; remove it +from a container as well: + +```sh +docker run --rm -v "$PWD/.scratch":/s alpine:3.20 rm -rf /s/target /s/cargo /s/rustup +``` + +What the image lacks, and what the tests do about it. A test that is about +the missing piece returns without testing it, in most cases after printing a +line that says it skipped and names the piece (the wording differs from test +to test), or is `#[ignore]`d with the reason, and passes; any other test does +not need the piece. + +| A test cannot count on | What the tests do | +|---|---| +| Regular user (root writes anywhere and creates missing directories) | Nothing relies on a permission bit or a missing directory failing. A path that cannot be written is built from something that fails for root too: below a regular file (`ENOTDIR`) or naming a directory (`EISDIR`), as `an_unwritable_path_fails_at_once` of the recorder does. | +| Sound card (`/dev/snd`), PipeWire and WirePlumber daemons | `libpipewire` and ALSA are there to build against only. `tests/pipewire_apps.rs` needs `pipewire`, `wireplumber` and `dbus-daemon` and, without them, prints a skipped line that names them. The camera tests are `#[ignore]`d (a camera and PipeWire). | +| D-Bus session bus | `voelin-platform`'s portal proxy test runs itself again under `dbus-run-session` on a bus of its own and, where that cannot be run, prints `skipped, nothing was checked: dbus-run-session cannot be run`; the notification and capture-portal tests run only where no bus is configured, and check that talking to a missing service fails cleanly. | +| GPU, `/dev/dri`, VA-API, `/dev/udmabuf` | The VA-API and DMA-BUF tests print a skipped line that names what is missing: a usable `h264_vaapi`, `/dev/udmabuf` or VA-API surfaces to export. | +| FFmpeg libraries, `ffmpeg` and `ffprobe` | The FFmpeg tests of `voelin-media` and `voelin-core` print a skipped line that names what is missing (the libraries, `ffmpeg`, `ffprobe`). The studio tests that read a recording back with `ffprobe` write and check the file themselves and skip only the `ffprobe` check; the RTMP tests need all three and skip. | +| H.264 encoder (no FFmpeg, no GPU, no OpenH264 library: `VOELIN_OPENH264_LIB` is unset and the download test is `#[ignore]`d) | Tests that need an H.264 encoder print a skipped line that says no H.264 encoder is there. Tests of codec choice state what `preferred_codec` promises with whatever the machine can encode. VP8 and VP9 (libvpx) are built in, so their round trips run. | +| X11 or Wayland display | `xvfb-run` supplies one X11 display and the step hands it over as `VOELIN_X11_TEST_DISPLAY` to the X11 capture and hotkey tests. `VOELIN_WLROOTS_TEST_DISPLAY` is unset, so the wlroots capture test prints `skipped`. | +| Playwright and Chromium (the image has Node) | The browser interop tests print `skipped: set VOELIN_INTEROP=1 (needs node, Playwright and Chromium)`. | +| TeamSpeak dev servers | Without `VOELIN_LIVE=1` the live tests return at once (some print `skipped: set VOELIN_LIVE=1 with the dev servers running`); the gateway's live test is `#[ignore]`d (`needs a running tsgw and TeamSpeak server`). | +| DNS and internet while the tests run (the job needs the network for apt, rustup and crates before they start) | The tests use no DNS or internet; those that would are `#[ignore]`d with the reason: four resolver tests of `tsclientlib` (`needs DNS and the internet`) and the OpenH264 download test. | + +`localhost` resolves to `::1` first in this image (it also has `127.0.0.1`). +The tests that reach a server of their own go to `127.0.0.1` by name, not +through `localhost`, so a machine where connections to `::1` hang (a +development machine with a VPN does that) changes nothing for them. + ### VoelinProtocol access The workspace depends on `voelin-identity` from the **private** repository