ashpd 0.13.13 keeps one session connection per process (a static in its
proxy.rs), and zbus 5.19 picks that connection's executor once, from
Handle::try_current() on the thread that builds it, when both its `tokio` and
`async-io` features are compiled in. The first ashpd caller therefore decided
the executor of every later portal call: a tokio caller first, then a caller
with no runtime (a GPUI foreground task), panics with "there is no reactor
running" (get_property("version") sets up zbus's property cache, which calls
tokio::task::spawn). The merged binary was safe only because GPUI's
colour-scheme call builds the connection before the engine's portal calls.
voelin-platform's notify-rust asks for `z` (async-io) in place of
`z-with-tokio`, and the stand-in portal's zbus dev-dependency for `async-io`
instead of `tokio`: a test binary with both features shows the panic even when
the binaries do not have it. `cargo tree -e features -i zbus` now names
`tokio` nowhere; Cargo.lock loses zbus's tokio edge and tokio's tracing edge
(THIRD_PARTY_NOTICES.md is unchanged).
tests/proxy.rs gets the gate's probe shape on a private dbus-run-session bus
(skipped with a printed reason where none can be made): a tokio caller first,
then a caller with no runtime. It fails with the panic on the tree before this
change, and still did with only notify-rust moved, which is why the
dev-dependency moved too.
The four records that described the move wrongly are corrected:
docs/design/gpui-spikes.md "Dependencies", the comment of
PortalCapture::start, voelin-media's Cargo.toml and CHANGELOG.md (whose
Slint-only sentence goes: the Slint app's zbus connections move to async-io
threads too).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
234 lines
8.8 KiB
Rust
234 lines
8.8 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 and third tests call ashpd from a thread with no tokio runtime,
|
|
//! as GPUI's executor would: ashpd runs on zbus's `async-io`, whichever thread
|
|
//! built its connection (the third lets a tokio caller build it first;
|
|
//! 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();
|
|
}
|
|
}
|
|
|
|
/// The stand-in portal on the bus of its own, served from the calling task.
|
|
async fn stand_in_portal(lookups: &Arc<AtomicU32>) -> zbus::Connection {
|
|
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 lookup through ashpd, from the calling task.
|
|
async fn lookup() -> Vec<ashpd::Uri> {
|
|
let resolver = ashpd::desktop::proxy_resolver::ProxyResolver::new().await.unwrap();
|
|
let uri = ashpd::Uri::parse("https://capped.example/").unwrap();
|
|
resolver.lookup(&uri).await.unwrap()
|
|
}
|
|
|
|
/// A lookup through ashpd from a thread of its own with no runtime, blocking
|
|
/// the caller's task for it (the pool's threads, `spawn_blocking`, have the
|
|
/// runtime in reach). The stand-in portal runs on the test's runtime: keep it
|
|
/// free while waiting.
|
|
async fn lookup_without_a_runtime() -> Vec<String> {
|
|
let caller = std::thread::spawn(|| {
|
|
assert!(tokio::runtime::Handle::try_current().is_err(), "this thread has no runtime");
|
|
block_on(lookup()).iter().map(|uri| uri.as_str().to_owned()).collect::<Vec<_>>()
|
|
});
|
|
tokio::task::spawn_blocking(move || caller.join().unwrap()).await.unwrap()
|
|
}
|
|
|
|
/// 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 = stand_in_portal(&lookups).await;
|
|
assert_eq!(lookup_without_a_runtime().await, ["socks://127.0.0.1:2080"]);
|
|
assert_eq!(lookups.load(Ordering::SeqCst), 1);
|
|
}
|
|
|
|
/// ashpd keeps one session connection for the process, and zbus picks the
|
|
/// executor of a connection once, when it builds it: tokio if a tokio runtime
|
|
/// is current on that thread and zbus has its `tokio` feature on, its own
|
|
/// `async-io` thread otherwise. If the engine's runtime made the connection
|
|
/// first, a later caller with no runtime (a GPUI foreground task) would find a
|
|
/// tokio connection with no reactor to run on and panic ("there is no reactor
|
|
/// running" in zbus's property cache). With zbus on `async-io` alone in every
|
|
/// binary (notify-rust without `z-with-tokio`, no zbus `tokio` here either)
|
|
/// the order does not matter.
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn the_portal_answers_a_caller_without_a_runtime_after_a_tokio_caller() {
|
|
const TEST: &str = "the_portal_answers_a_caller_without_a_runtime_after_a_tokio_caller";
|
|
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 = stand_in_portal(&lookups).await;
|
|
// The tokio caller first: it builds the process's session connection.
|
|
let answer: Vec<_> = lookup().await.iter().map(|uri| uri.as_str().to_owned()).collect();
|
|
assert_eq!(answer, ["socks://127.0.0.1:2080"]);
|
|
// Then the caller with no runtime, on the same connection.
|
|
assert_eq!(lookup_without_a_runtime().await, ["socks://127.0.0.1:2080"]);
|
|
assert_eq!(lookups.load(Ordering::SeqCst), 2);
|
|
}
|