GPUI's Linux backend enables ashpd's `async-io` feature, and ashpd 0.13.13 refuses `async-io` and `tokio` at once (compile_error! in its lib.rs), so a binary could not hold the portals and gpui-kit. voelin-media's `pipewire` feature (the screen-cast and camera portals) and voelin-platform's `portal` feature (global shortcuts, file chooser, proxy resolver) now ask ashpd for `async-io`; Cargo.lock loses ashpd's edge to tokio and nothing else (the package set is the same: THIRD_PARTY_NOTICES.md is unchanged and `scripts/notices.sh --check` clean). What zbus 5.19 does with the features (read in its abstractions/mod.rs): with both `async-io` and `tokio` compiled in it picks per connection, tokio when a tokio runtime is current on the calling thread, else async-io with an I/O thread of its own. The workspace has both on already (notify-rust asks for zbus/tokio, secret-service and others for its defaults), so the engine's portal calls, which run inside its tokio runtime, still use tokio; a caller with no runtime (GPUI's foreground executor) gets the I/O thread. Built on its own, voelin-media has `async-io` only. The source needed no change beyond a doc comment (capture/portal.rs said the connection needs a tokio runtime). tests/proxy.rs gains a second test on the same stand-in portal: ashpd's ProxyResolver called from a thread with no tokio runtime, polled by hand, gets the answer. Both tests run again under `dbus-run-session` on a bus of their own (the harness takes the test's name). Checked on Rust 1.95.0: fmt and clippy (-D warnings, --no-deps) of the own crates; `cargo test -p voelin-platform -p voelin-media`: all pass, including tests/proxy.rs (2 tests), the portal-less-bus tests of both crates run with no session bus (`unavailable_without_session_bus`, the `proxy::tests` that need none), and tests/pipewire_apps.rs against a private PipeWire and WirePlumber (found on PATH, ran: 2 passed in 2.7 s). The live portal (a desktop's screen-cast dialog, the shortcut binding) was not exercised: no desktop session is used by these runs. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
196 lines
6.9 KiB
Rust
196 lines
6.9 KiB
Rust
//! The desktop's proxy through a stand-in xdg-desktop-portal on a session
|
|
//! bus. The test runs itself again under `dbus-run-session` on a bus of its
|
|
//! own that starts no services: on a desktop's bus the real portal is running
|
|
//! or startable, and when the stand-in leaves the bus (as the test has it do)
|
|
//! the real one is started and answers instead. Without `dbus-run-session`,
|
|
//! or a bus daemon for it, the test says so and checks nothing. Its own test
|
|
//! binary: answers are kept process-wide.
|
|
//!
|
|
//! The second test calls ashpd from a thread with no tokio runtime, as GPUI's
|
|
//! executor would: ashpd runs on zbus's `async-io` there (docs/design/gpui-spikes.md,
|
|
//! "Dependencies").
|
|
|
|
#![cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
|
|
|
|
use std::sync::Arc;
|
|
use std::sync::atomic::{AtomicU32, Ordering};
|
|
|
|
use voelin_platform::proxy::proxy_for;
|
|
|
|
/// Set for the run on the bus of its own.
|
|
const ON_ITS_OWN_BUS: &str = "VOELIN_PROXY_TEST_ON_ITS_OWN_BUS";
|
|
|
|
/// What the GNOME portal answers: a SOCKS proxy for one host, none for the
|
|
/// others.
|
|
struct Resolver {
|
|
lookups: Arc<AtomicU32>,
|
|
}
|
|
|
|
#[zbus::interface(name = "org.freedesktop.portal.ProxyResolver")]
|
|
impl Resolver {
|
|
fn lookup(&self, uri: &str) -> Vec<String> {
|
|
self.lookups.fetch_add(1, Ordering::SeqCst);
|
|
if uri.starts_with("https://capped.example") {
|
|
vec!["socks://127.0.0.1:2080".into()]
|
|
} else {
|
|
vec!["direct://".into()]
|
|
}
|
|
}
|
|
|
|
#[zbus(property)]
|
|
fn version(&self) -> u32 {
|
|
1
|
|
}
|
|
}
|
|
|
|
/// The configuration of the bus of its own: a session bus without the service
|
|
/// directories, so that nothing on it can be started by name. Its socket is
|
|
/// made in `dir`.
|
|
fn bus_config(dir: &std::path::Path) -> String {
|
|
format!(
|
|
r#"<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
|
|
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
|
|
<busconfig>
|
|
<type>session</type>
|
|
<listen>unix:tmpdir={}</listen>
|
|
<auth>EXTERNAL</auth>
|
|
<policy context="default">
|
|
<allow send_destination="*" eavesdrop="true"/>
|
|
<allow eavesdrop="true"/>
|
|
<allow own="*"/>
|
|
</policy>
|
|
</busconfig>
|
|
"#,
|
|
dir.display()
|
|
)
|
|
}
|
|
|
|
/// Run the test `name` again under `dbus-run-session` on a bus of its own, and
|
|
/// say nothing was checked when that bus cannot be had.
|
|
fn on_a_bus_of_its_own(name: &str) {
|
|
let dir = std::env::temp_dir();
|
|
let config = dir.join(format!("voelin-proxy-test-bus-{}-{name}.conf", std::process::id()));
|
|
std::fs::write(&config, bus_config(&dir)).unwrap();
|
|
let run = std::process::Command::new("dbus-run-session")
|
|
.arg(format!("--config-file={}", config.display()))
|
|
.arg("--")
|
|
.arg(std::env::current_exe().unwrap())
|
|
.args(["--exact", name, "--nocapture", "--test-threads=1"])
|
|
.env(ON_ITS_OWN_BUS, "1")
|
|
.output();
|
|
let _ = std::fs::remove_file(&config);
|
|
let run = match run {
|
|
Ok(run) => run,
|
|
Err(e) => {
|
|
eprintln!("skipped, nothing was checked: dbus-run-session cannot be run ({e})");
|
|
return;
|
|
}
|
|
};
|
|
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.
|
|
assert!(
|
|
!text.contains("running 1 test"),
|
|
"the test failed on its own bus ({}):\n{text}",
|
|
run.status
|
|
);
|
|
eprintln!("skipped, nothing was checked: no bus of its own could be started:\n{text}");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn the_portal_names_the_proxy() {
|
|
if std::env::var_os(ON_ITS_OWN_BUS).is_none() {
|
|
on_a_bus_of_its_own("the_portal_names_the_proxy");
|
|
return;
|
|
}
|
|
let lookups = Arc::new(AtomicU32::new(0));
|
|
let portal = zbus::connection::Builder::session()
|
|
.unwrap()
|
|
.name("org.freedesktop.portal.Desktop")
|
|
.unwrap()
|
|
.serve_at("/org/freedesktop/portal/desktop", Resolver { lookups: lookups.clone() })
|
|
.unwrap()
|
|
.build()
|
|
.await
|
|
.unwrap();
|
|
let proxy = proxy_for("https://capped.example:443/").await;
|
|
assert_eq!(proxy.as_deref(), Some("socks5h://127.0.0.1:2080"));
|
|
assert_eq!(proxy_for("https://other.example/").await, None);
|
|
assert_eq!(lookups.load(Ordering::SeqCst), 2);
|
|
// Kept: the same scheme, host and port are not asked again.
|
|
let proxy = proxy_for("https://capped.example/a/b.png").await;
|
|
assert_eq!(proxy.as_deref(), Some("socks5h://127.0.0.1:2080"));
|
|
assert_eq!(lookups.load(Ordering::SeqCst), 2);
|
|
// The portal leaves the bus: missing for a minute, not asked meanwhile.
|
|
const PORTAL: &str = "org.freedesktop.portal.Desktop";
|
|
assert!(portal.release_name(PORTAL).await.unwrap());
|
|
assert_eq!(proxy_for("https://gone.example/").await, None);
|
|
portal.request_name(PORTAL).await.unwrap();
|
|
assert_eq!(proxy_for("https://capped.example:8443/").await, None);
|
|
assert_eq!(lookups.load(Ordering::SeqCst), 2);
|
|
}
|
|
|
|
/// Run `future` on the calling thread, which parks while it waits: an executor
|
|
/// of no runtime at all, as a GPUI foreground task is to ashpd.
|
|
fn block_on<F: std::future::Future>(future: F) -> F::Output {
|
|
struct Unpark(std::thread::Thread);
|
|
impl std::task::Wake for Unpark {
|
|
fn wake(self: Arc<Self>) {
|
|
self.0.unpark();
|
|
}
|
|
}
|
|
let waker = std::task::Waker::from(Arc::new(Unpark(std::thread::current())));
|
|
let mut cx = std::task::Context::from_waker(&waker);
|
|
let mut future = std::pin::pin!(future);
|
|
loop {
|
|
if let std::task::Poll::Ready(output) = future.as_mut().poll(&mut cx) {
|
|
return output;
|
|
}
|
|
std::thread::park();
|
|
}
|
|
}
|
|
|
|
/// ashpd with `async-io`: a caller outside any tokio runtime gets its answer,
|
|
/// the connection's I/O running on zbus's own thread.
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn the_portal_answers_a_caller_without_a_runtime() {
|
|
const TEST: &str = "the_portal_answers_a_caller_without_a_runtime";
|
|
if std::env::var_os(ON_ITS_OWN_BUS).is_none() {
|
|
on_a_bus_of_its_own(TEST);
|
|
return;
|
|
}
|
|
let lookups = Arc::new(AtomicU32::new(0));
|
|
let _portal = zbus::connection::Builder::session()
|
|
.unwrap()
|
|
.name("org.freedesktop.portal.Desktop")
|
|
.unwrap()
|
|
.serve_at("/org/freedesktop/portal/desktop", Resolver { lookups: lookups.clone() })
|
|
.unwrap()
|
|
.build()
|
|
.await
|
|
.unwrap();
|
|
// A thread of its own: the pool's threads (`spawn_blocking`) have the
|
|
// runtime in reach.
|
|
let caller = std::thread::spawn(|| {
|
|
assert!(tokio::runtime::Handle::try_current().is_err(), "this thread has no runtime");
|
|
block_on(async {
|
|
let resolver = ashpd::desktop::proxy_resolver::ProxyResolver::new().await.unwrap();
|
|
let uri = ashpd::Uri::parse("https://capped.example/").unwrap();
|
|
resolver.lookup(&uri).await.unwrap()
|
|
})
|
|
});
|
|
// The stand-in portal runs on this runtime: keep it free while waiting.
|
|
let answer = tokio::task::spawn_blocking(move || caller.join().unwrap()).await.unwrap();
|
|
let answer: Vec<&str> = answer.iter().map(|uri| uri.as_str()).collect();
|
|
assert_eq!(answer, ["socks://127.0.0.1:2080"]);
|
|
assert_eq!(lookups.load(Ordering::SeqCst), 1);
|
|
}
|